How to Design Error Response Format for REST APIs
Design error responses using a consistent
JSON structure that includes fields like status, error, and message. This helps clients easily understand and handle errors in your REST API.Syntax
An error response format typically includes these parts:
- status: HTTP status code (e.g., 404, 500)
- error: Short error type or code (e.g., "Not Found")
- message: Human-readable explanation of the error
- details (optional): Additional info or validation errors
json
{
"status": 404,
"error": "Not Found",
"message": "The requested resource was not found.",
"details": {
"resource": "user",
"id": "123"
}
}Example
This example shows a simple REST API error response in JSON format when a user is not found.
python
import json def get_user(user_id): users = {"1": "Alice", "2": "Bob"} if user_id not in users: error_response = { "status": 404, "error": "Not Found", "message": f"User with id {user_id} does not exist.", "details": {"user_id": user_id} } return json.dumps(error_response), 404 return json.dumps({"id": user_id, "name": users[user_id]}), 200 # Simulate calling the function response, status_code = get_user("3") print(response) print("HTTP Status:", status_code)
Output
{"status": 404, "error": "Not Found", "message": "User with id 3 does not exist.", "details": {"user_id": "3"}}
HTTP Status: 404
Common Pitfalls
Common mistakes when designing error responses include:
- Using inconsistent field names or formats across endpoints.
- Returning only HTTP status codes without a message, making it hard for clients to understand the error.
- Including sensitive internal details in error messages.
- Not using standard HTTP status codes properly.
json
Wrong:
{
"code": 404,
"msg": "User not found"
}
Right:
{
"status": 404,
"error": "Not Found",
"message": "User not found"
}Quick Reference
| Field | Description | Example |
|---|---|---|
| status | HTTP status code | 404 |
| error | Short error type | "Not Found" |
| message | Human-readable explanation | "User not found" |
| details | Optional extra info | {"user_id": "3"} |
Key Takeaways
Use a consistent JSON structure with status, error, and message fields for all error responses.
Include clear, human-readable messages to help clients understand the problem.
Avoid exposing sensitive internal details in error messages.
Use standard HTTP status codes to indicate error types clearly.
Optional details can provide extra context but keep them concise and safe.