Status codes, error shapes and messages that shorten debugging instead of prolonging it. A guide to writing API errors that people can actually fix.
When an API call fails, the developer is already annoyed. The error response is their only clue. A vague message like “Bad request” sends them to a search engine, a support ticket or a competitor. A clear one gets them moving again in a minute.
Start with the right status code
The status code is the first signal, and tools and caches rely on it. Use the range correctly: 4xx when the caller can fix it, 5xx when the problem is on your side. For a full tour, see our guide to HTTP methods and status codes.
Use one consistent shape
Every error from your API should look the same, so clients can write one piece of handling code. A good shape includes a machine readable code, a human readable message, and a pointer to the field when relevant.
{
"error": {
"code": "invalid_parameter",
"message": "The 'quantity' field must be a whole number greater than 0.",
"field": "quantity",
"request_id": "req_8f2a91",
"docs_url": "https://example.com/docs/errors#invalid_parameter"
}
}There is also a published standard for this called Problem Details (RFC 9457), with the content type application/problem+json. Using it saves you from inventing your own format.
Write messages that help
Compare these two messages for the same problem:
- Say what is wrong, and where.
- Say how to fix it, or what a valid value looks like.
- Do not blame the user. Describe the input, not the person.
- Avoid internal jargon and stack traces in the message.
Validation errors: report all of them
If a form has three mistakes, return three errors at once. Making someone fix one, resubmit, and discover the next is slow and frustrating.
{
"error": {
"code": "validation_failed",
"message": "2 fields need attention.",
"details": [
{ "field": "email", "message": "Must be a valid email address." },
{ "field": "age", "message": "Must be 18 or older." }
]
}
}Be careful what you reveal
- Never expose stack traces, SQL or file paths to outside callers. Log them privately instead.
- For login failures, do not reveal whether the email or the password was wrong.
- For
404on resources the caller may not access, consider whether revealing existence is a leak. - Always include a request ID, so you can investigate without exposing internals.