How to Choose the Right HTTP Status Code
Pick correct HTTP status codes for success, redirect, client error, and server error cases, and avoid the 200-with-an-error-field anti-pattern.
On this page
Introduction
The status code is the first thing every client, cache, proxy, and monitor looks at. A response that returns 200 for an error forces every consumer to parse the body to find out what happened, and it breaks the assumptions of retry logic, caching, and alerting, all of which key on the status. Choosing the status is therefore an interface decision with downstream consequences, not a cosmetic detail.
This tutorial walks through the four status classes, the specific codes that APIs use most, the common traps such as 200-with-an-error-field and 500-for-a-client mistake, and how to test the mapping. The examples use Node.js, but the codes are protocol-level and the reasoning applies to any framework.
Start from the outcome
Classify the outcome first. If the request was handled and a representation is returned, it is 2xx. If the resource moved, it is 3xx. If the request itself is the problem, it is 4xx. If the server failed despite a valid request, it is 5xx. This ordering prevents the common error of returning 500 for a malformed client request or 200 for a server failure. Classify before you pick the number.
Within a class, the code carries meaning that clients act on. A 401 tells the client to authenticate; a 403 tells it that authenticating again will not help. A 409 tells it to resolve a conflict and retry; a 429 tells it to slow down. Choosing the vague code in a class loses that signal and invites a client to do the wrong thing.
Pick the specific code
For success, 200 for a general success with a body, 201 for a created resource with a Location header, 202 for accepted asynchronous work, and 204 for success with no body. Returning 200 with an empty body where 204 is correct confuses clients that check for content. For redirects, use the permanent or temporary code that matches intent and preserves the method where needed.
For client errors, use 400 for a malformed request, 401 when credentials are missing or invalid, 403 when the caller is authenticated but not permitted, 404 for a missing resource, 409 for a conflict such as a duplicate or a stale edit, 412 when a precondition such as If-Match fails, 413 for an oversized body, 422 for semantic validation failure, and 429 for rate limiting. For server errors, 500 for an unexpected failure, 502 and 503 for upstream and unavailable conditions, and 504 for an upstream timeout.
function statusFor(outcome) {
switch (outcome.kind) {
case 'created': return 201;
case 'accepted': return 202;
case 'no-content': return 204;
case 'bad-request': return 400;
case 'unauthenticated': return 401;
case 'forbidden': return 403;
case 'not-found': return 404;
case 'conflict': return 409;
case 'precondition-failed': return 412;
case 'validation': return 422;
case 'rate-limited': return 429;
case 'upstream-timeout': return 504;
default: return 500;
}
}
Fail loudly, not silently
The anti-pattern of returning 200 with a body such as { “success”: false, “error”: “…” } defeats every layer that looks at the status. A proxy may cache the response as a success, a retry library may not retry, and a monitor may count it as healthy. Return an error status and put the details in the body, ideally using a standard error shape such as the Problem Details format so clients parse it uniformly.
Similarly, do not use 500 for client mistakes. A 500 signals that the server is broken and typically triggers alerts and retries, while a 400 tells the client to fix its request. Returning 500 for a validation failure floods on-call with noise and hides real server failures in the same bucket.
function sendProblem(res, status, type, title, detail) {
res.writeHead(status, { 'content-type': 'application/problem+json' });
res.end(JSON.stringify({ type, title, status, detail }));
}
sendProblem(res, 422, 'https://errors.example.com/validation', 'Validation failed', 'email is not a valid address');
Map errors to codes in one place
Centralize the mapping from internal errors to status codes. If each handler decides its own status, the API becomes inconsistent and a refactor can change the contract by accident. Define a set of error types with a status each, translate at the boundary, and keep the handler code free of status decisions. This makes the mapping testable and reviewable.
Be careful with security-sensitive distinctions. Do not reveal whether a resource exists to an unauthorized caller if that leaks information; in some cases 404 is preferable to 403 to avoid confirming existence. Decide this per resource and document it, rather than defaulting to the more informative code everywhere.
Test the status mapping
For each endpoint, assert the status for the success case, the validation failure, the authentication failure, the authorization failure, and the not-found case. Assert that a body that fails validation returns 422 or 400, not 500. Assert that a conflict returns 409 and that a failed precondition returns 412. Finally, assert that an unexpected exception is caught and returned as a 500 rather than crashing the connection with no response.
curl -s -o /dev/null -w '%{http_code}\n' -X POST -d '{}' -H 'content-type: application/json' http://localhost:3000/orders # 422
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:3000/orders/does-not-exist # 404
curl -s -o /dev/null -w '%{http_code}\n' -H 'If-Match: "stale"' -X PATCH http://localhost:3000/orders/1 -d '{}' # 412
Common pitfalls
Returning 200 with an error field, using 500 for client mistakes, using 403 where 401 is correct, returning 200 with an empty body instead of 204, conflating 400 and 422 inconsistently, and letting each handler pick its own status are the recurring mistakes. A single error-to-status mapping and a per-endpoint status test address all of them.
Conclusion
The status code is an interface, so choose it from the outcome and use the specific code that carries the right signal. Return error statuses for errors instead of 200-with-an-error-field, avoid 500 for client mistakes, and centralize the mapping so it stays consistent. Self-check by asserting the status for success, validation, auth, authorization, conflict, and not-found on every endpoint. Correct codes make retries, caches, and alerts behave without any client having to read the body to know what happened.
Sources: MDN: HTTP response status codes, RFC 9110: Status codes, RFC 9457: Problem Details for HTTP APIs.
FAQ
- When should I return 204 instead of 200?
- Use 204 No Content when the request succeeded and there is deliberately no response body, such as a DELETE or an update with no representation to return. A 200 with an empty body is ambiguous; 204 states that no body is intended.
- 400 or 422 for validation errors?
- 400 Bad Request covers syntactically invalid requests, while 422 Unprocessable Entity covers well-formed requests that fail semantic validation. Many APIs use 400 for both; the important thing is to choose one and apply it consistently and to include enough detail for the client to fix the request.
Report a problem with this articleOpens a pre-filled issue on GitHub.