How to design API error responses
error response schema, problem details RFC 7807, machine-readable errors, error codes vs status codes, validation error format, developer experience
How to design API error responses
Errors Are Part of Your API
A well-designed error response is as important as a successful one. If a developer cannot understand your error, they will build broken retry logic or ship a bad user experience. Be precise and be consistent.
Use RFC 7807: Problem Details
RFC 7807 defines a standard error format. Adopt it:
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/problem+json
{
"type": "https://api.myapp.com/errors/validation",
"title": "Validation Failed",
"status": 422,
"detail": "The request body contains invalid fields.",
"errors": [
{ "field": "email", "message": "Must be a valid email address" },
{ "field": "age", "message": "Must be at least 18" }
]
}Key Principles
Never expose stack traces in production responses — they leak internal architecture. Log them server-side. Return a requestId field so developers can correlate client errors to server logs. Use a stable type URI as a machine-readable error code so clients can branch logic without parsing free-text messages. Make errors consistent: every 4xx across every endpoint must follow the same schema. Inconsistency forces developers to write defensive parsing code for every endpoint they integrate.
