download

Which HTTP status code and error format fit each API failure?

Backend~9 minReviewed 3 Dec 2026Free · No sign-in

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.

  1. Why is returning 200 OK for failures harmful for clients and infrastructure?
  2. Choose from 400, 401, 403, 404, 409, 422, 429, and 503 for eight failures. Map broken JSON, negative quantity, missing token, non-admin token, missing order, duplicate email, rate limit, and overloaded database.
  3. Replace the helper with an RFC 9457 application/problem+json response that includes Retry-After when appropriate.
"CODE · PYTHON"
def handle_error(exc):
    return 200, {"Content-Type": "application/json"}, {
        "ok": False,
        "error": repr(exc),
    }
Show hints (3)
  1. "SPLIT 4XX AND 5XX"

    Use 4xx when the caller must change the request or wait. Use 5xx when the server failed to process a valid call.

  2. "STANDARD ERROR SHAPE"

    RFC 9457 uses Content-Type: application/problem+json with type, title, status, and safe detail fields. Never include raw tracebacks.

  3. "GUIDE CLIENT RETRIES"

    Pair 429 and 503 with a Retry-After header 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.

"SOLUTION · PYTHON"
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"])
"OUTPUT"
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):

StatusFailure caseSafe to retry?
400Broken JSON syntax or bad framingNo; fix syntax
401Missing or expired auth tokenOnly after re-auth
403Valid token, lacks permissionNo
404Order ID does not existNo
409Duplicate email or version clashOnly after resolving state
422Valid JSON, negative quantityNo; fix field values
429Rate limit reachedYes, after Retry-After
503Database or upstream overloadedYes, 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 OK with an error field. Load balancers report 100% success during an outage, and HTTP caches can store the failed payload.
  • Confusing 401 and 403. 401 means missing or invalid credentials; 403 means you know who the caller is, and they lack rights.
  • Leaking str(exc) or stack traces in detail. That exposes SQL schemas and library versions while giving callers nothing actionable.
  • Returning 500 for 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 Request when the HTTP request or JSON syntax cannot even be parsed. Use 422 Unprocessable Content when 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 (or instance URI) in the Problem Details body and X-Request-Id header. 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-Authenticate on 401 responses so clients know which scheme to use, such as Bearer. 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 →

Original OfferVibe question. RFC 9457 Problem Details · RFC 9110 HTTP Semantics · RFC 6585 Additional HTTP Status Codes · MDN HTTP Status Codes · MDN Retry-After.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.