JSON API Tutorial for Beginners
Learn to build and consume REST APIs with JSON. Complete guide with practical examples, code snippets, and best practices.
What You'll Learn in This Guide
π Part 1-5
Chapter 1: What is an API?
API (Application Programming Interface) is a set of rules that allows different software applications to communicate with each other. Think of it as a waiter in a restaurant - you (the client) place an order, the waiter (API) takes it to the kitchen (server), and brings back your food (response).
- π Over 50,000+ public APIs available today
- π± 90% of developers use APIs in their applications
- π° API economy projected to reach $7.5 trillion by 2026
- β‘ APIs power everything from weather apps to payment gateways
How APIs Work
Client (Your App) β API Request β Server Client (Your App) β API Response β Server
Simple analogy: You ask a question (request) β API delivers it β You get an answer (response)
Types of APIs
- REST APIs: Most common, uses HTTP, lightweight
- SOAP APIs: Older protocol, more rigid, XML-based
- GraphQL APIs: Newer, lets clients request specific data
- WebSocket APIs: Real-time, bidirectional communication
Chapter 2: REST API Basics
REST (Representational State Transfer) is an architectural style for designing APIs. REST APIs use HTTP requests to perform CRUD (Create, Read, Update, Delete) operations.
REST API Constraints
Separation of concerns - UI separate from data storage
Each request contains all necessary information. Server doesn't store client context
Responses can be cached to improve performance
Consistent resource identification and representation
REST API Structure
https://api.example.com/v1/users/123
Parts:
β’ https://api.example.com - Base URL
β’ /v1 - API Version
β’ /users - Resource endpoint
β’ /123 - Specific resource ID
Chapter 3: JSON Data Format
JSON (JavaScript Object Notation) is the standard data format for REST APIs. It's lightweight, human-readable, and easy for machines to parse.
JSON Syntax
{
"name": "John Doe",
"age": 30,
"email": "john@example.com",
"isActive": true,
"hobbies": ["reading", "coding", "gaming"],
"address": {
"street": "123 Main St",
"city": "Mumbai",
"zipcode": "400001"
}
}
JSON Data Types
- String: "Hello World" (in double quotes)
- Number: 42, 3.14 (no quotes)
- Boolean: true or false (no quotes)
- Array: ["item1", "item2"] (ordered list)
- Object: {"key": "value"} (nested data)
- Null: null (empty value)
JSON is more compact, faster to parse, and easier to read than XML. It's the preferred format for modern REST APIs.
Parsing JSON in Different Languages
JSON.parse(jsonString); JSON.stringify(object);
import json json.loads(jsonString) json.dumps(dict)
json_decode($jsonString); json_encode($array);
ObjectMapper mapper = new ObjectMapper(); mapper.readValue(jsonString, Class.class);
Chapter 4: HTTP Methods (CRUD Operations)
APIs use HTTP methods to indicate the desired action on a resource. Each method has a specific purpose and meaning.
| Method | CRUD Action | Description | Example |
|---|---|---|---|
| GET | Read | Retrieve data (safe & idempotent) | GET /users |
| POST | Create | Create new resource | POST /users |
| PUT | Update (Full) | Replace entire resource | PUT /users/123 |
| PATCH | Update (Partial) | Partially update resource | PATCH /users/123 |
| DELETE | Delete | Remove resource | DELETE /users/123 |
Example Request & Response
GET https://api.example.com/v1/users
Headers: {
"Authorization": "Bearer token123",
"Content-Type": "application/json"
}
Response:
{
"status": "success",
"data": [
{"id": 1, "name": "John Doe", "email": "john@example.com"},
{"id": 2, "name": "Jane Smith", "email": "jane@example.com"}
],
"total": 2
}
Chapter 5: API Endpoints & Routing
Endpoints are specific URLs that represent resources in your API. Good endpoint design makes your API intuitive and easy to use.
RESTful Endpoint Design Principles
- Use nouns, not verbs:
/usersnot/getUsers - Use plural for collections:
/productsnot/product - Use nested resources for relationships:
/users/123/orders - Use query parameters for filtering:
/users?status=active&limit=10 - Use hyphens for readability:
/user-profilesnot/userProfiles
| β Good | GET /products?category=electronics |
| β Bad | GET /getAllProductsByCategory?cat=electronics |
| β Good | POST /orders |
| β Bad | POST /createNewOrder |
Common API Endpoint Patterns
GET /users - List all users GET /users/123 - Get user with ID 123 POST /users - Create a new user PUT /users/123 - Update user 123 (full) PATCH /users/123 - Update user 123 (partial) DELETE /users/123 - Delete user 123 GET /users/123/orders - Get orders for user 123 GET /products?category=books - Filter products
Chapter 6: API Authentication
Authentication verifies the identity of users or applications accessing your API. Here are the most common methods:
Simple, unique tokens passed via headers or query parameters.
X-API-Key: your-api-key-here
JSON Web Tokens containing user claims and expiration.
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
Username and password encoded in Base64.
Authorization: Basic dXNlcjpwYXNz
Industry standard for delegated access (Google, Facebook login).
access_token=xyz123
JWT Example
// JWT Structure: header.payload.signature
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJ1c2VySWQiOjEyMywidXNlcm5hbWUiOiJqb2huIn0.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
// Decoded payload
{
"userId": 123,
"username": "john",
"exp": 1735689600
}
β Use HTTPS always β Never expose API keys in client-side code β Rotate keys regularly β Use short-lived tokens β Implement rate limiting
Chapter 7: Error Handling & Status Codes
Proper error handling helps API consumers understand what went wrong and how to fix it.
HTTP Status Codes
| Code Range | Category | Common Codes |
|---|---|---|
| 2xx | Success | 200 OK, 201 Created, 204 No Content |
| 3xx | Redirection | 301 Moved, 304 Not Modified |
| 4xx | Client Error | 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many Requests |
| 5xx | Server Error | 500 Internal Error, 502 Bad Gateway, 503 Service Unavailable |
Standard Error Response Format
{
"status": "error",
"code": 400,
"message": "Invalid email format",
"errors": [
{
"field": "email",
"message": "Email must contain @ symbol"
}
],
"timestamp": "2024-10-15T10:30:00Z"
}
- β Include a meaningful message
- β Provide field-specific details when possible
- β Include a request ID for debugging
- β Use consistent error structure across endpoints
Chapter 8: API Versioning
API versioning allows you to make changes without breaking existing clients. Here are the main approaches:
Versioning Strategies
Most common approach, easy to implement.
https://api.example.com/v1/users
Simple but less common.
https://api.example.com/users?version=1
Clean URLs, but more complex.
Accept: application/vnd.example.v1+json
Uses Accept header.
Accept: application/json; version=1
β’ Support old versions for at least 6-12 months β’ Deprecate gradually with warning headers β’ Document breaking changes clearly β’ Use semantic versioning (v1, v1.1, v2)
Chapter 9: API Testing Tools
Testing APIs is crucial before integrating them into applications. Here are the best tools:
Most popular API testing tool. Create collections, write tests, automate workflows.
Free tier available - Perfect for beginners
Open-source alternative to Postman. Lightweight and fast.
100% Free & Open Source
Command-line tool for testing APIs. Available on all operating systems.
curl -X GET https://api.example.com/users
VS Code extension for API testing. Lightweight and integrated.
Best for VS Code users
Sample API Test (Postman Collection)
// Postman Test Script
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
pm.test("Response has users array", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.data).to.be.an('array');
});
pm.test("Response time < 500ms", function () {
pm.expect(pm.response.responseTime).to.be.below(500);
});
Chapter 10: API Best Practices
- Use HTTPS for all API endpoints
- Implement rate limiting to prevent abuse
- Use proper HTTP status codes
- Return consistent error responses
- Version your API (e.g., /v1/)
- Use pagination for large datasets
- Document your API (Swagger/OpenAPI)
- Compress responses with gzip
- Use query parameters for filtering, sorting, and pagination
- Implement logging and monitoring
- Set up proper CORS headers for browser clients
- Cache responses where appropriate
Public APIs to Practice With
- JSONPlaceholder: Fake REST API for testing β
https://jsonplaceholder.typicode.com/users - PokΓ©API: PokΓ©mon data API β
https://pokeapi.co/api/v2/pokemon/ditto - OpenWeatherMap: Weather data (requires API key) β
https://api.openweathermap.org/data/2.5/weather - GitHub API: GitHub data (public endpoints) β
https://api.github.com/users/octocat
β Using verbs in URLs β Not versioning APIs β Exposing internal implementation details β Inconsistent error handling β No rate limiting β Sensitive data in GET requests β Missing pagination for large responses
Free Developer Tools from Tyzo
Use these free tools for your API development and testing:
Frequently Asked Questions
Ready to build your first API?
Start with our free JSON tools and practice with public APIs.