+91 98726 60544 hello@mitstech.co Mon–Sat · 09:00–18:30 IST

API errors: what to return when something goes wrong

Cloud By Mits Engineering Team 2 min read
API errors: what to return when something goes wrong

Error responses are the part of an API that gets designed last and used most during integration. A developer wiring up your API spends their first week almost entirely in the failure paths, and what you return determines whether they fix their own mistakes or open a support ticket for each one. It is worth as much design attention as the success case.

Use status codes for their actual meaning, because tooling depends on it. 400 for a malformed request, 401 when authentication is missing or invalid, 403 when the caller is authenticated but not permitted, 404 for something that does not exist, 409 for a conflict with current state, 422 when the syntax is fine but the values are not, 429 for rate limiting. Returning 200 with an error in the body - which some APIs do - defeats every retry policy, monitoring tool and HTTP client in the chain.

The body should be consistent across every endpoint and machine-readable. A stable error code the client can branch on, a human-readable message for the developer reading logs, and for validation failures a list of which fields failed and why. The critical property is that the code is stable and the message is not: clients will parse whatever you give them, so if the only distinguishing feature is prose, you can never reword it.

Distinguish clearly between errors the caller can fix and errors they cannot. A validation failure needs specifics - which field, what was wrong, what was expected. A server-side failure needs the opposite: a generic message and a correlation identifier they can quote to your support team, with the detail in your logs rather than in the response. Internal exception messages, stack traces, SQL fragments and library versions leaked in error bodies are reconnaissance for anyone probing you.

Tell clients whether retrying will help, because they cannot infer it. A 429 should carry Retry-After. A 503 during deployment is worth retrying; a 400 never is. Without that signal, well-behaved clients retry things that will never succeed, and badly-behaved ones retry immediately in a loop - and either way, your error responses have generated additional load at exactly the wrong moment.

Two details that save disproportionate support time. Return every validation failure at once rather than one at a time, so a developer fixes six problems in one pass instead of six round trips. And include a correlation identifier on every error, logged alongside the full detail on your side - it turns a bug report of 'it returned an error' into a single log lookup, which is the difference between five minutes and an afternoon.

Need help with this? Explore our Cloud Solutions & Migration services. Learn more Back to all news

Keep reading

More on Cloud