How-to › Make calls that survive failure

How to choose the HTTP status for each error your API returns#

Give each failure class one HTTP status, write the rule down, and check every status in your OpenAPI description against it, so no status means two things.

Audience
API producer
Level
beginner
Topic
Handle and design API errors
Verified

Your payment endpoint answers 409 when an order is already paid, and the update endpoint answers 409 when the caller’s ETag is stale. A client that sees 409 cannot tell whether to fetch again and retry or to stop, so it treats both failures the same way and gets one of them wrong. Two engineers each chose a reasonable status, and the choice was never written down.

What you get

You will end up with a rule file that gives each error status one meaning, and a checker that fails when the OpenAPI description uses a status two ways. This is for you if more than one person adds endpoints to the API.

Short answer

Write a rule that gives each failure class one status. Use 400 when a request does not parse and 422 when a parsed field breaks a rule. Use 401 for a missing credential, 403 for a refused action, and 404 when the caller may not see the resource. Use 409 for a state conflict and 412 for a failed If-Match. Then check every status in the OpenAPI description against that rule.

You will need

An HTTP API you are designing, its OpenAPI description, and Node 22 or later to run the checker. Verified 2026-11-30 against Node 22.23.5. Every status below is defined in RFC 9110, except 429, which comes from RFC 6585, and 499, which neither defines.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
GitHub REST status conventionsA public API with private resources and field-level validation404 stands for missing, private and wrong method, so a client learns little from it aloneCallers need to tell a missing resource from a forbidden one
gRPC canonical status mappingYou also expose gRPC, or want a small fixed set clients handle in one switchThree codes share 400 and three share 500, so the status alone cannot route a retryClients act on the status before they read the body
Stripe status conventionsA payments API where the body’s error type carries the detail400 covers validation, so 422 never appears and every client must parse the bodyField errors must be distinguishable from unparseable requests by status

GitHub spends statuses on distinctions it wants clients to see, 400 against 422, and hides one it does not, 403 behind 404. gRPC maps 17 codes onto 12 statuses and puts the distinction in the code, so its HTTP side is the smallest set here. Stripe sits between the two, with a short list and a type field in every error body. A small set is easier to handle; a larger one tells a client what to do before it parses anything.

Settle the five arguments

Each pair below is where two reasonable engineers pick differently. Pick once, for the whole API.

400 against 422. Use 400 when the request cannot be parsed and 422 when it parses and a field breaks a rule. RFC 9110 defines 422 for content whose syntax is correct but which the server cannot process. GitHub draws the same line: a body that is not JSON gets 400, a missing field gets 422. Stripe’s table lists 400 for a missing required parameter and no 422 at all.

401 against 403. Use 401 when the credential is missing, expired or invalid, and 403 when the caller is known and the action is refused. A 401 must carry WWW-Authenticate, which section 15.5.2 makes a MUST.

404 against 403. Use 404 when the caller may not learn that the resource exists, and 403 only when it can already see the resource. The 404 definition covers a server that will not disclose whether the resource exists, and GitHub returns 404 instead of 403 for private repositories for that reason.

409 against 412. Use 412 only when the caller sent a conditional header, such as If-Match, and it evaluated to false, as section 15.5.13 defines. Use 409 for every other clash with the resource’s state. A client that gets 412 fetches the resource again and retries, and that is the wrong response to an order that is already paid.

500 against 502 and 503. Use 500 for a fault in your service, 502 when a service you call failed you, and 503 with Retry-After for overload or maintenance. A client may retry a 503 after the wait. A 500 that repeats is a bug to report, not a load to wait out.

Write the rule down

The rule is a file, one entry per error status, each naming the shared response component every endpoint must use for it.

{
  "400": { "response": "MalformedRequest", "meaning": "The request cannot be parsed: broken JSON, a wrong content type, a query string that does not decode." },
  "401": { "response": "Unauthenticated", "meaning": "No credential, or one that is expired or invalid. Sent with WWW-Authenticate." },
  "403": { "response": "Forbidden", "meaning": "The caller can see the resource but may not perform this action on it." },
  "404": { "response": "NotFound", "meaning": "No resource the caller is allowed to see exists at this URL." },
  "409": { "response": "Conflict", "meaning": "The request clashes with the resource's state: a duplicate, or a transition its state does not allow." },
  "412": { "response": "PreconditionFailed", "meaning": "An If-Match or If-Unmodified-Since header the caller sent evaluated to false." },

Tying a status to a component under components/responses is what makes “one meaning” checkable. Two endpoints that both answer 409 with $ref: '#/components/responses/Conflict' mean the same thing by construction. An inline response or a second component is a second meaning.

Check every status against the rule

check-statuses.mjs walks every operation and lists each status with the component it points at. It fails on a status with two meanings, a status the rule lacks, a range such as 4XX, a $ref it cannot resolve, and a 2xx body with an error or errors property.

node check-statuses.mjs openapi.json status-rules.json
openapi.json: 5 operations
  200  success                 3 operations
  201  success                 2 operations
  400  MalformedRequest        3 operations
  401  Unauthenticated         5 operations
  403  Forbidden               3 operations
  404  NotFound                4 operations
  409  Conflict                4 operations
  412  PreconditionFailed      1 operation
  422  ValidationFailed        3 operations
  429  RateLimited             5 operations
  500  InternalError           5 operations
  502  UpstreamFailed          1 operation
  503  Unavailable             2 operations
ok: every status has exactly one meaning

Success statuses are listed but not compared, because a 200 means whatever its operation returns.

Check it worked

Run the checker on drifted.json, the same API after three careless edits. The update endpoint answers a stale ETag with a second 409 component, the read endpoint grew an inline 403, and cancel returns 200 with an error field.

node check-statuses.mjs drifted.json status-rules.json
FAIL GET /orders/{id}: 403 points at inline "Not your order.", the rule says Forbidden
FAIL PUT /orders/{id}: 409 points at VersionMismatch, the rule says Conflict
FAIL POST /orders/{id}/cancel: 200 body has an "error" property; send an error status instead
FAIL 403 carries 2 meanings: inline "Not your order." (GET /orders/{id}) and Forbidden (PUT /orders/{id}, POST /orders/{id}/cancel, POST /orders/{id}/payments)
FAIL 409 carries 2 meanings: Conflict (POST /orders, POST /orders/{id}/cancel, POST /orders/{id}/payments) and VersionMismatch (PUT /orders/{id})
5 problem(s)

It exits 1, so CI stops on it. The tests apply one broken edit at a time to the passing document, twelve in all, and expect each to fail on its own.

node --test statuses.test.mjs
1..18
# tests 18
# suites 0
# pass 18
# fail 0
# cancelled 0
# skipped 0
# todo 0

When it goes wrong

A failed request reports success. The endpoint returned 200 with an error field, so a client that checks the status first, as the wrapper in pitfall.mjs does, took the body as a result:

node pitfall.mjs
200 with an error field  -> resolved, caller sees {"cancelled":false,"error":"order already shipped"}
409 problem details      -> threw ApiError 409: HTTP 409: order already shipped

Return the error status and put the detail in the body. The checker refuses an error property in a 2xx schema for this reason.

A client cannot tell which 400 it got. That is the trade the gRPC mapping makes, measured here from the recorded code.proto:

node grpc.mjs
17 gRPC codes onto 12 HTTP statuses (google/rpc/code.proto in the google-proto-files npm package, version 6.1.0)
  200  OK
  400  INVALID_ARGUMENT, FAILED_PRECONDITION, OUT_OF_RANGE   <- 3 meanings
  401  UNAUTHENTICATED
  403  PERMISSION_DENIED
  404  NOT_FOUND
  409  ALREADY_EXISTS, ABORTED   <- 2 meanings
  429  RESOURCE_EXHAUSTED
  499  CANCELLED
  500  UNKNOWN, INTERNAL, DATA_LOSS   <- 3 meanings
  501  UNIMPLEMENTED
  503  UNAVAILABLE
  504  DEADLINE_EXCEEDED

If you follow that mapping, the gRPC code in the body is the meaning, and the rule file lists the code rather than the status.1

When not to do this

Do not invent a status for every failure. RFC 9110 requires a client to treat a status it does not recognize as the x00 of its class, so a client that never heard of your 4xx reads it as 400. Put the business reason in the body, under a stable type, and keep the status set small.

Do not change a published status to make the rule tidy. A client that branches on 400 breaks when the same failure starts answering 422, so give the change a version or a deprecation window.

Do not run this checker on a description that uses default or 4XX on purpose, such as one whose errors all share a single default response. It refuses ranges by design, so adopt its rule or adapt the code first.

Last verified

Verified 2026-11-30 against Node 22.23.5. Every output block is what the command preceding it printed. Stripe’s and GitHub’s conventions are read from their documentation, without calling either API. The gRPC mapping was recorded from google-proto-files 6.1.0 by record.sh.

Footnotes

  1. The mapping lives in comments. Each code in code.proto carries a line such as HTTP Mapping: 400 Bad Request on the line before it. The same file tells a service to use ABORTED when the client should restart a read-modify-write sequence, which HTTP signals with 412 after a failed If-Match, but maps ABORTED to 409. CANCELLED maps to 499 Client Closed Request, a number the IANA status code registry lists as unassigned. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.