Skip to content

API errors and status codes

A client acts on a failed request through three layers. The status code tells generic software (browsers, proxies, caches, retry logic, monitors) the class of failure. The problem type tells the client application which situation it is. Both are part of the API contract. The text helps developers understand the error without revealing internals.

Use these defaults for new HTTP API versions and existing alpha versions. See evolving a public contract for stable versions and API design for the rest of the interface.

Use RFC 9457 problem details and Content-Type: application/problem+json for 4xx and 5xx responses the API controls. A HEAD response is bodyless (RFC 9110 section 9.3.2). Health probes use the body defined in health checks.

{
"type": "https://api.example.com/problems/invalid-email",
"title": "Invalid email address",
"status": 422,
"detail": "Enter an email address in the form name@example.com.",
"errors": [{"detail": "Enter an email address in the form name@example.com.", "pointer": "#/email"}]
}
  • type is the machine-readable code. A client decides what to do and what to show by type, never by text. Mint a type for each situation a client handles differently, and none for what the status already says: such a problem uses about:blank, with the status phrase as its title (RFC 9457 section 4, 4.2.1).
  • Use an absolute HTTPS URL for a new problem type. It resolves to documentation under a domain we control. Use a short English name in kebab-case for the last segment. Clients use the URI as the type’s identity, so changing it changes the contract (RFC 9457 section 3.1.1).
  • status equals the status of the response (RFC 9457 section 3.1.2).
  • title summarizes the problem type, and detail describes this occurrence to help the client correct it (RFC 9457 sections 3.1.3 and 3.1.4).
  • Extension members carry what a client acts on, such as the limit that was reached or the item that conflicts.
  • errors lists the field errors, each with a detail and either a pointer (JSON Pointer) into the body or the parameter name of a query, path or header field. List every field error in one answer, so a form marks all its fields at once. When problems of different types meet in one request, answer the most relevant one (RFC 9457 section 3).
  • The OpenAPI document lists every type each operation answers, with its status. That list is the contract.

Identifiers are English and never translated: type, member names and field names. title and detail are English as well. They are written for the developer who integrates the API and for our logs, not for end users.

A frontend shows the end user its own translated text, chosen by type, and a generic translated text for a type it does not know (translations), never detail. So a refusal an end user has to understand in their own language, such as an email address the mail server refuses, gets a type of its own; a field detail alone cannot be translated.

No response names our components or passes on their texts. That covers the database, cache, queue, identity provider, payment provider and mail relay, host names, exception messages, upstream error texts, stack traces, SQL, file paths and versions, in every status and every environment. Such details help an attacker map the system (RFC 9457 section 5, OWASP error handling), the client cannot act differently on them, and a client that starts relying on a text turns our internals into contract.

A failure on our side answers one generic text per status, such as “The service is unavailable for a moment; retry the request later.” for a 503. The cause goes to the logs and Sentry. A typed problem about a third party the customer knows, such as a VAT number check that cannot run, names the subject (“The VAT number cannot be checked now.”), not the system behind it.

Never echo a secret. A key, token or password does not appear in an error, not even masked. Echoing a parameter value back is fine when it is the client’s own input and helps to find it.

A hidden target answers the same 404 as a missing target. Answer 403 only when the caller may know the resource exists, such as a member whose role does not allow the change (RFC 9110 section 15.5.4). A hidden resource referenced by an input field gets the same validation response as a missing one.

Sign-in, registration and password reset do not reveal whether an account exists. They answer the same status, body and timing for a known and an unknown address: sign-in “The email address or password is wrong.”, a password reset “If an account has this address, we emailed a link.” A registration for a taken address answers as a new one does and emails the owner instead (OWASP authentication). Their rate limit counts per address as well, whether or not the address has an account.

Every 5xx and every unexpected exception reaches Sentry with the full cause, without secrets (secure development). A 4xx is the client’s outcome, not our error: log it and count it per type, so a rise shows on a dashboard, but do not report each one to Sentry.

Every request carries an id. The proxy at the edge sets it, or the application creates one when it is missing, and passes it on as X-Request-ID, the name proxies and frameworks already use. Each log line and the Sentry event (as tag request_id) carry it, and the response returns it in X-Request-ID, so a customer or frontend can quote it and support finds the cause. A browser frontend reads it only when CORS lists it in Access-Control-Expose-Headers.

Use the most specific registered code whose definition in the RFC matches, never a code for what its name suggests, and never an invented one. One situation answers one status and one type, so no code means two things to a client.

SituationStatus
The request has malformed syntax, broken framing, or an invalid path, query or header parameter400
The body has a media type the operation does not take415
A well-formed body fails validation422
No credentials, or unknown, expired or revoked ones401
Valid credentials that do not allow this: role, plan, scope, inactive subscription, origin403
No matching route, or the target resource is missing or hidden404
The path does not offer the method405
The request is valid, but the current state refuses it: duplicate, wrong state, stale edit409
A precondition the client sent, such as If-Match, does not hold412
The body is larger than the operation takes413
The client sent too many requests or used up its quota429
The endpoint was removed on purpose410
A bug or other unexpected condition500
A gateway or proxy received an invalid or unusable upstream response502
The service is temporarily unavailable: dependency outage, overload or maintenance503
A gateway or proxy did not receive a timely upstream response504

A search or list without matches is no error: it answers 200 with an empty list. A lookup of one thing that is not there is 404.

After accepting HTTP framing, match the route and method (404, 405), authenticate the caller (401), and check permission to use the operation (403). Validate the parameters needed to identify the target, then resolve the target and check access to it. Validate the rest of the input before checking for state conflicts (409). Check any permission tied to an input value as soon as the value is valid.

400 or 422. Use 400 for malformed syntax, such as invalid JSON, and for missing or invalid parameters outside the request body (RFC 9110 section 15.5.1). Use 422 when the body uses a supported media type and valid syntax but fails validation, such as a missing required field or an invalid value (RFC 9110 section 15.5.21).

401 or 403. 401 when other credentials could succeed: none were sent, or they are unknown, expired or revoked. The client may refresh or replace them and retry (RFC 9110 section 15.5.2). 403 when the credentials are valid but do not grant this, so repeating the request with them cannot succeed (RFC 9110 section 15.5.4): a role, a plan without the feature, an inactive or unpaid subscription, a request from outside the origins or addresses the key allows. A frontend that refreshes its token on 401 loops when such a refusal answers 401, and a monitor reports broken credentials for a plan question. For bearer tokens, invalid_token answers 401 and insufficient_scope 403 (RFC 6750 section 3.1). Never use 402: it is reserved (RFC 9110 section 15.5.3).

403 or 409. 403 refuses the caller; 409 refuses the request in the current state of the resource. A key whose subscription is inactive gets 403 on every call. An account that creates a key on its own inactive subscription gets 409: the same request succeeds once the subscription is active.

403 or 404. Use 404 to conceal a request target. See what an answer may reveal for access denials and hidden input references.

404 or a validation error. Use 404 when the requested target is missing, including a lookup for one resource identified by a query parameter (RFC 9110 section 15.5.5). For example, GET /projects/123 returns 404 if project 123 is missing. In POST /tasks with {"projectId": 123}, the missing project makes the body invalid. Return 422 with a pointer to #/projectId. Use 400 and a parameter name when a missing reference makes an input parameter invalid.

409 or 422. Use 409 when valid input conflicts with the current state, such as creating an item that already exists or changing a paid invoice. The client re-reads and resolves the conflict (RFC 9110 section 15.5.10). Use 422 when the body fails validation. When the client sent a precondition such as If-Match, its failure is 412 (RFC 9110 section 15.5.13). A retry of a creation that already succeeded answers that success again rather than 409, when the server can tell it is the same request, such as by an id the client chose.

429, 403 or 503 for a limit. A client over its rate or quota gets 429 (RFC 6585 section 4), a plan without the feature 403, and a service that is overloaded for everyone 503.

500, 502, 503 or 504. 503 when we cannot serve the request ourselves: our database or connection pool is unavailable, the service is overloaded or in maintenance (RFC 9110 section 15.6.4). When the application is acting as a gateway for an upstream operation, use 502 for an invalid or unusable reply and 504 for a timeout (15.6.3, 15.6.5). Use 500 for an unexpected server failure. An upstream outage is a server-side error. A proxy uses 404 for an unknown public route and a 5xx for a configured route that it cannot serve (Zalando).

Never a 200 with an error, never a 5xx for a client mistake

Section titled “Never a 200 with an error, never a 5xx for a client mistake”

A 2xx means success to every generic tool: caches store it, retry logic stops, uptime monitors and error rates count it as served, and fetch() reports it as ok. An error behind a 200 hides from all of them.

A 5xx denotes a server-side failure and is recorded for monitoring. Retry behavior depends on the status and the operation (see retrying). Validate input of an unexpected type, encoding or media type into a 4xx before the handler sees it.

Framework defaults break these rules, so every API installs its own handlers: FastAPI answers malformed JSON with 422 and {"detail": ...} instead of problem details, and Flask answers its errors with HTML pages. A catch-all handler answers an unexpected exception with the generic 500 problem.

HeaderOnRule
Content-Type: application/problem+jsonEvery problemRFC 9457 section 3
WWW-AuthenticateEvery 401Required (RFC 9110 section 11.6.1)
AllowEvery 405Required, every method the path offers (section 10.2.1)
Retry-After429, 503 or 413 with a known retry timeDelay in seconds (section 10.2.3)
Accept415The media types the operation takes (section 15.5.16)
Cache-ControlEvery errorno-store, or a lifetime when the answer is the same for every caller
CORS headersEvery response to an allowed originWithout them the browser hides an error from the frontend
X-Request-IDEvery answerThe id of the request (logging the cause)

For bearer authentication, challenge with Bearer realm="...". Include error="invalid_token" on 401 for a rejected token. Omit the error code when credentials are absent. An invalid authentication request, such as sending the token by two methods, uses 400 and invalid_request (RFC 6750 section 3). A cache may keep a 404, 405 or 410 that states no lifetime (RFC 9110 section 15.1, RFC 9111 section 4.2.2) and hand it to another client, and a 429 is never stored (RFC 6585 section 4). An answer that depends on the credentials is no-store: with private, the browser still reuses it after an account switch. Every 404 of a route that hides resources carries the same headers, so they do not tell a hidden resource from a missing one.

StatusRetry
400, 405, 415, 422No: correct the request
413Only after Retry-After; without it, correct the request
401Once, after refreshing or replacing the credentials
403, 404, 410No
409After re-reading the state and resolving the conflict, never blindly
412After fetching the current version and resolving the failed condition
429, 502, 503, 504Yes, with exponential backoff and jitter
500No automatic retry

Cap retries and honor Retry-After when present. Clients accept both delay seconds and an HTTP date (RFC 9110 section 10.2.3). Automatically retry only when the operation is idempotent or when the client can establish that the original request was never applied (RFC 9110 section 9.2.2).

Clients, our own frontends included, handle what they do not know by its class:

  • An unknown status as the x00 of its class, so 451 as 400 and 507 as 500 (RFC 9110 section 15).
  • An unknown problem type as about:blank with its status: act on the status and show the generic text for it.
  • Unknown extension members are ignored (RFC 9457 section 3.2).
  • A body that is no problem at all, such as the HTML 502 of a proxy, is handled by its status.
  • title and detail are never parsed (RFC 9457 section 3.1.4).

The contract is the status and type per situation and the documented members. Texts are not: clients do not parse them, so they can improve at any time.

Adding is compatible, because clients handle the unknown by its class: a type for a situation that did not exist, an extension member, a field error. Changing what an existing situation answers breaks clients that branch on it: another status or type, a member removed, one type split where clients act on the old one, another body format.

An alpha API may change its error format, status codes and types in place before it stabilizes. Announce breaking changes in the changelog and tell affected integrators what to update.

A stable API preserves its published error format, status codes and type identifiers within the version. Introduce breaking changes in the next version and follow deprecating features. Ship related status and type changes together so integrators only have to adapt once.

The API documentation holds one table of every status and type with when it happens. It is what customers code against, so it changes in the same commit as the code. A deprecated operation answers with Deprecation and Sunset headers until its cutoff, and with 410 after it.