Which HTTP status code and error format fit each API failure?
Question
Your billing API wraps every error in HTTP 200 OK using the helper below. Callers cannot tell whether to re-authenticate, fix their input, or retry later, and raw database exceptions leak into the JSON.
- Why is returning
200 OKfor failures harmful for clients and infrastructure? - Choose from
400,401,403,404,409,422,429, and503for eight failures. Map broken JSON, negativequantity, missing token, non-admin token, missing order, duplicate email, rate limit, and overloaded database. - Replace the helper with an RFC 9457
application/problem+jsonresponse that includesRetry-Afterwhen appropriate.
def handle_error(exc): return 200, {"Content-Type": "application/json"}, { "ok": False, "error": repr(exc), }
Show hints (3)
- "SPLIT 4XX AND 5XX"
Use
4xxwhen the caller must change the request or wait. Use5xxwhen the server failed to process a valid call. - "STANDARD ERROR SHAPE"
RFC 9457 uses
Content-Type: application/problem+jsonwithtype,title,status, and safedetailfields. Never include raw tracebacks. - "GUIDE CLIENT RETRIES"
Pair
429and503with aRetry-Afterheader so clients know how many seconds to wait before trying again.
Show checked explanation
Never wrap API failures in 200 OK. Proxies, CDNs, metrics, and HTTP clients rely on status codes to cache, alert, and retry safely. Return accurate 4xx/5xx codes with Content-Type: application/problem+json (RFC 9457), add Retry-After on 429 and 503, and log internal stack traces only on the server.
def problem(status, title, detail, retry_after=None): headers = {"Content-Type": "application/problem+json"} if retry_after is not None: headers["Retry-After"] = str(retry_after) body = {"type": "about:blank", "title": title, "status": status, "detail": detail} return status, headers, body cases = [ (400, "Bad Request", "Malformed JSON body", None), (422, "Unprocessable Content", "quantity must be positive", None), (429, "Too Many Requests", "Rate limit reached", 30), (503, "Service Unavailable", "Upstream busy", 5), ] for args in cases: code, hdrs, body = problem(*args) print(code, hdrs["Content-Type"], hdrs.get("Retry-After"), body["title"])
400 application/problem+json None Bad Request 422 application/problem+json None Unprocessable Content 429 application/problem+json 30 Too Many Requests 503 application/problem+json 5 Service Unavailable
Ran the starter and RFC 9457 helper on CPython 3.12.10 and tested all eight status codes over a local http.server. Checked by an editor other than the author.
Walkthrough
Returning 200 OK with {"ok": false} breaks the whole HTTP stack. Reverse proxies and dashboards count 200 as healthy traffic, hiding outages from alerts. Caches may even store a 200 error response and serve it to other users. Generic retry libraries cannot tell a permanent client mistake from a temporary outage.
Pick the narrowest standard status code from RFC 9110 (plus RFC 6585 for 429):
| Status | Failure case | Safe to retry? |
|---|---|---|
400 | Broken JSON syntax or bad framing | No; fix syntax |
401 | Missing or expired auth token | Only after re-auth |
403 | Valid token, lacks permission | No |
404 | Order ID does not exist | No |
409 | Duplicate email or version clash | Only after resolving state |
422 | Valid JSON, negative quantity | No; fix field values |
429 | Rate limit reached | Yes, after Retry-After |
503 | Database or upstream overloaded | Yes, after Retry-After |
Use RFC 9457 Problem Details. Set Content-Type: application/problem+json and include type, title, status, and detail. Keep the JSON status identical to the HTTP status line. When type is "about:blank", match title to the standard HTTP reason phrase. For domain-specific cases, set type to a stable URI like https://api.example.com/problems/out-of-stock and add structured extension fields such as errors or request_id.
Add Retry-After on temporary blocks. Both 429 (RFC 6585) and 503 (RFC 9110) tell callers to slow down. Sending Retry-After: 30 (delay seconds or an HTTP-date) stops clients from hammering a struggling server.
Keep internals private. Putting repr(exc) in JSON leaks table names, SQL queries, and file paths. Return a clear client-safe detail plus a request_id, and log the full traceback server-side.
Common mistakes
- Returning
200 OKwith anerrorfield. Load balancers report 100% success during an outage, and HTTP caches can store the failed payload. - Confusing
401and403.401means missing or invalid credentials;403means you know who the caller is, and they lack rights. - Leaking
str(exc)or stack traces indetail. That exposes SQL schemas and library versions while giving callers nothing actionable. - Returning
500for malformed client JSON or negative quantities. That pages on-call engineers for ordinary caller mistakes.
Follow-up questions
- "When should you choose 400 instead of 422 for a bad JSON request?" Use
400 Bad Requestwhen the HTTP request or JSON syntax cannot even be parsed. Use422 Unprocessable Contentwhen the JSON parses cleanly but fails field rules, such as a negative quantity or unknown enum value. - "How does a caller debug a 500 or 503 error if you hide the stack trace?" Return a non-secret
request_id(orinstanceURI) in the Problem Details body andX-Request-Idheader. Log that same ID alongside the stack trace internally so support can look up the exact failure. - "Why should a 401 response include a WWW-Authenticate header?" RFC 9110 requires
WWW-Authenticateon401responses so clients know which scheme to use, such asBearer. It tells automated clients how to obtain or refresh credentials.
What a strong answer covers
Explains how 200 OK errors break monitoring, caching, and retries. Maps all eight failure cases to accurate RFC 9110 and RFC 6585 status codes, uses RFC 9457 application/problem+json with Retry-After, and keeps internal tracebacks out of responses.
Open in interactive practice deck →