Understanding REST API JSON Responses
What is a REST API?
A REST API (Representational State Transfer Application Programming Interface) is a standardised way for two systems to communicate over the internet using HTTP. When a mobile app shows a user's profile, when a weather widget displays the current temperature, or when an e-commerce site loads a product listing — all of these are powered by REST APIs in the background.
In modern REST APIs, data is almost always exchanged in JSON format. The client (browser or app) sends a request, and the server sends back a JSON response. Understanding how to read and interpret these responses is a fundamental skill for any web or app developer.
Anatomy of an HTTP Request and Response
When a client talks to a REST API, it sends an HTTP request and receives an HTTP response. The response has two main parts:
- Status Code — a number that tells the client whether the request succeeded or failed
- Response Body — the actual data, usually in JSON format
Common HTTP Status Codes in JSON APIs
| Status Code | Meaning | Common Situation |
|---|---|---|
| 200 OK | Request succeeded | Successfully fetched data |
| 201 Created | New resource was created | Successfully submitted a form or new record |
| 400 Bad Request | Request was invalid | Missing required field or bad data format |
| 401 Unauthorized | Authentication required | No valid login token provided |
| 403 Forbidden | Access denied | Logged in but no permission for this resource |
| 404 Not Found | Resource does not exist | Requested ID or URL does not exist on server |
| 500 Internal Server Error | Server-side failure | A bug or crash occurred on the server |
Common REST API JSON Response Patterns
While there is no single universal standard, most well-designed REST APIs follow consistent patterns. Understanding these patterns helps in quickly working with any API.
Pattern 1 — Single Resource Response
When fetching a single item (like one user, one product, or one article), the API returns a single JSON object:
{
"id": 14,
"name": "Shobha Rani",
"email": "shobha@example.com",
"phone": "9901234567",
"address": {
"city": "Mysore",
"state": "Karnataka"
},
"createdAt": "2024-06-10T08:45:00Z"
}Pattern 2 — List / Collection Response
When fetching multiple items (like all products or all users), the API typically returns a JSON array, often wrapped inside a parent object along with metadata:
{
"status": "success",
"total": 3,
"data": [
{
"id": 1,
"title": "Introduction to JSON",
"author": "Ravi Shankar"
},
{
"id": 2,
"title": "JSON with Python",
"author": "Meena Kumari"
},
{
"id": 3,
"title": "REST API Best Practices",
"author": "Arun Verma"
}
]
}Pattern 3 — Success/Error Response Wrapper
Most professional APIs include a standard wrapper that always has a status field (and sometimes a message field) so the client can check at a glance whether the operation succeeded:
// Success Response
{
"status": "success",
"message": "User created successfully.",
"data": {
"userId": 205,
"name": "Tanveer Malik",
"email": "tanveer@example.com"
}
}
// Error Response
{
"status": "error",
"message": "Email address is already registered.",
"code": 409
}Pattern 4 — Paginated Response
When a dataset is large, APIs return data in pages. The response includes pagination metadata so the client knows how many pages there are and how to request the next one:
{
"status": "success",
"page": 1,
"perPage": 10,
"totalRecords": 87,
"totalPages": 9,
"data": [
{ "id": 1, "product": "Pen", "price": 10 },
{ "id": 2, "product": "Notebook", "price": 50 }
],
"nextPage": "https://api.example.com/products?page=2"
}Reading a Real API Response in JavaScript
Using the public test API at jsonplaceholder.typicode.com:
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(function(response) {
console.log("Status:", response.status); // Output: 200
return response.json();
})
.then(function(post) {
console.log("Post ID:", post.id); // Output: 1
console.log("Title:", post.title);
console.log("User ID:", post.userId);
})
.catch(function(err) {
console.log("Error:", err);
});Handling the Error Response in JavaScript
Always check the status before processing. A successful HTTP connection does not mean the API request itself was successful — the status code must be checked:
fetch("https://jsonplaceholder.typicode.com/posts/9999")
.then(function(response) {
if (response.status === 404) {
return { error: true, message: "Post not found." };
}
return response.json();
})
.then(function(data) {
if (data.error) {
console.log("Error: " + data.message);
} else {
console.log("Title: " + data.title);
}
});Sending a Request to an API with JSON Body
const newUser = {
name: "Vinaya Patil",
email: "vinaya@example.com",
role: "student"
};
fetch("https://jsonplaceholder.typicode.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(newUser)
})
.then(function(response) {
return response.json();
})
.then(function(created) {
console.log("New user created with ID: " + created.id);
});REST API HTTP Methods and Their Purpose
| HTTP Method | Action | Example |
|---|---|---|
| GET | Fetch / read data | Get a user's profile |
| POST | Create new data | Register a new user |
| PUT | Replace / fully update data | Replace all fields of a product |
| PATCH | Partially update data | Change only the price of a product |
| DELETE | Remove data | Delete a blog post |
Key Points to Remember
- REST APIs use HTTP to send and receive JSON data between client and server
- Always check the HTTP status code — 2xx means success, 4xx means client error, 5xx means server error
- Most APIs return a JSON object with a
statusordatawrapper field - Paginated responses include metadata like
page,totalPages, andnextPage - Use
JSON.parse()to read incoming JSON andJSON.stringify()to send JSON in the request body - Always set the
Content-Type: application/jsonheader when sending JSON data
Summary
Understanding how REST APIs structure their JSON responses is essential for building and consuming modern web services. Recognising common patterns — single resource, list with pagination, success/error wrappers — makes it much easier to integrate with any API quickly. The combination of JSON, the Fetch API, and an understanding of HTTP methods and status codes forms the complete toolkit for working with real-world web APIs.
