# 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.

Source: https://voxgig.com/howto/choose-the-http-status-for-each-error

- Audience: api-producer
- Level: beginner
- Verified: 2026-11-30
- Published: 2026-11-30

## 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](https://www.rfc-editor.org/rfc/rfc9110.html#section-15), except 429, which comes from
[RFC 6585](https://www.rfc-editor.org/rfc/rfc6585.html#section-4), and 499, which neither defines.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [GitHub REST status conventions](https://docs.github.com/en/rest/using-the-rest-api/troubleshooting-the-rest-api) | A public API with private resources and field-level validation | 404 stands for missing, private and wrong method, so a client learns little from it alone | Callers need to tell a missing resource from a forbidden one |
| [gRPC canonical status mapping](https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto) | You also expose gRPC, or want a small fixed set clients handle in one switch | Three codes share 400 and three share 500, so the status alone cannot route a retry | Clients act on the status before they read the body |
| [Stripe status conventions](https://docs.stripe.com/api/errors) | A payments API where the body's error type carries the detail | 400 covers validation, so 422 never appears and every client must parse the body | Field 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](https://www.rfc-editor.org/rfc/rfc9110.html#section-15.5.21) 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](https://docs.github.com/en/rest/using-the-rest-api/troubleshooting-the-rest-api#problems-parsing-json),
a missing field gets [422](https://docs.github.com/en/rest/using-the-rest-api/troubleshooting-the-rest-api#validation-failed).
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](https://www.rfc-editor.org/rfc/rfc9110.html#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](https://docs.github.com/en/rest/using-the-rest-api/troubleshooting-the-rest-api#404-not-found-for-an-existing-resource)
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](https://www.rfc-editor.org/rfc/rfc9110.html#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](https://www.rfc-editor.org/rfc/rfc9110.html#section-15.6.3) when a service you call failed
you, and [503](https://www.rfc-editor.org/rfc/rfc9110.html#section-15.6.4) 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.

```json title="status-rules.json"
{
  "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.

```bash
node check-statuses.mjs openapi.json status-rules.json
```

```text output
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.

```bash
node check-statuses.mjs drifted.json status-rules.json
```

```text output
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.

```bash
node --test statuses.test.mjs
```

```text output
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:

```bash
node pitfall.mjs
```

```text output
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`:

```bash
node grpc.mjs
```

```text output
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](https://www.rfc-editor.org/rfc/rfc9110.html#section-15)
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.

## Related how-tos

- [Design error responses an autonomous agent can act on](/howto/error-responses-an-agent-can-act-on)

- [Verify every error response matches one schema](/howto/verify-every-error-response-matches-one-schema)

- [Evolve an error contract without breaking clients](/howto/evolve-an-error-contract-without-breaking-clients)

- [Translate upstream API errors behind your own API](/howto/translate-upstream-errors-behind-your-api)

- [Honor Retry-After without stalling a worker pool](/howto/honour-retry-after-without-stalling-a-worker-pool)

## 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`.

[^1]: The mapping lives in comments. Each code in
[`code.proto`](https://github.com/googleapis/googleapis/blob/master/google/rpc/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](https://www.iana.org/assignments/http-status-codes) lists as
unassigned.