0
0
Rest-apiHow-ToBeginner ยท 4 min read

How to Design API Response Body: Best Practices and Examples

To design an API response body, use a consistent JSON structure with clear keys like status, data, and error. Include meaningful messages and data, and keep the format simple and predictable for easy client use.
๐Ÿ“

Syntax

An API response body usually follows a JSON format with these parts:

  • status: A string or number indicating success or failure.
  • data: The main content or result of the API call.
  • error: Details about any error, if occurred.
  • message: A human-readable message for clarity.

This structure helps clients understand the response quickly.

json
{
  "status": "success",
  "data": { /* your data here */ },
  "error": null,
  "message": "Request completed successfully"
}
๐Ÿ’ป

Example

This example shows a simple API response for a user info request. It returns status, user data, and a message.

javascript
const exampleResponse = {
  status: "success",
  data: {
    id: 123,
    name: "Alice",
    email: "alice@example.com"
  },
  error: null,
  message: "User data fetched successfully"
};

console.log(JSON.stringify(exampleResponse, null, 2));
Output
{ "status": "success", "data": { "id": 123, "name": "Alice", "email": "alice@example.com" }, "error": null, "message": "User data fetched successfully" }
โš ๏ธ

Common Pitfalls

Common mistakes when designing API response bodies include:

  • Using inconsistent key names across endpoints.
  • Returning raw data without wrapping it in a clear structure.
  • Omitting error details or using unclear error messages.
  • Mixing data types unpredictably, making parsing hard.

Always keep the response format consistent and clear.

json
/* Wrong way: inconsistent keys and no error info */
{
  "result": { "id": 1, "name": "Bob" },
  "msg": "OK"
}

/* Right way: consistent keys and error field */
{
  "status": "success",
  "data": { "id": 1, "name": "Bob" },
  "error": null,
  "message": "OK"
}
๐Ÿ“Š

Quick Reference

FieldDescriptionExample
statusIndicates success or failure"success" or "error"
dataContains the main response data{"id": 1, "name": "Alice"}
errorError details if anynull or {"code": 404, "message": "Not found"}
messageHuman-readable message"User created successfully"
โœ…

Key Takeaways

Use a consistent JSON structure with keys like status, data, error, and message.
Always include clear error information when requests fail.
Keep the response simple and predictable for easy client parsing.
Use meaningful messages to help users and developers understand the response.
Avoid mixing different formats or inconsistent key names across your API.