Request and Response Design
How you structure API requests and responses shapes the developer experience. Consistent shapes make integration straightforward. Clear error responses help developers fix problems quickly. Thoughtful design here pays dividends every time someone uses your API.
Request Design
Keep request bodies focused and predictable. Include only what's needed to perform the action:
POST /users
{
"email": "alice@example.com",
"name": "Alice Smith",
"role": "admin"
}
Don't require clients to send data the server should generate — IDs, timestamps, and computed fields belong in responses, not requests.
Response Design
Wrap data in a consistent envelope. This provides room for metadata without changing the core structure:
{
"data": {
"id": 123,
"email": "alice@example.com",
"name": "Alice Smith",
"role": "admin",
"createdAt": "2024-01-15T10:30:00Z"
}
}
For collections, the envelope accommodates pagination information:
{
"data": [...],
"pagination": {
"total": 150,
"page": 1,
"perPage": 20
}
}
Error Response Design
Errors deserve as much design attention as successes. A good error response tells developers exactly what went wrong:
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Email is invalid",
"details": [
{"field": "email", "message": "Must be valid email format"},
{"field": "name", "message": "Required field"}
]
}
}
Machine-readable codes (VALIDATION_ERROR) enable programmatic handling. Human-readable messages help during development. Field-level details pinpoint exactly what needs fixing.
HTTP Status Codes
Use status codes correctly — they're the first thing clients check:
| Code | Meaning | When to Use |
|---|---|---|
| 200 | OK | Successful GET, PUT, PATCH |
| 201 | Created | Successful POST that creates resource |
| 204 | No Content | Successful DELETE |
| 400 | Bad Request | Invalid input from client |
| 401 | Unauthorized | Missing or invalid authentication |
| 403 | Forbidden | Authenticated but not permitted |
| 404 | Not Found | Resource doesn't exist |
| 500 | Server Error | Something broke on your end |
Don't return 200 with an error in the body — that forces clients to parse responses to detect failures.
Timestamps and Formats
Use ISO 8601 for dates (2024-01-15T10:30:00Z) and include timezone information. Use consistent casing — camelCase is common in JSON APIs.