API-3Recommended
Answer with the right status code
Pick the status code that matches what happened. Never answer 200 with an error inside the body.
How to do it
Follow the table below, from RFC 9110 and RFC 6585. Use 5xx only for faults on your side, never for bad input. When two codes could fit, pick the more specific one. Honest codes let the error rate count failures.
Examples
| Code | When |
|---|---|
| 200 | A read or update that returns a body |
| 201 | A create, with a Location header pointing to the new resource |
| 202 | Work accepted but not done yet |
| 204 | Success with no body |
| 400 | A body that does not parse, such as broken JSON, or a bad query or path parameter |
| 401 | Credentials missing, expired or wrong |
| 403 | Valid credentials that may not do this |
| 404 | Unknown resource, or one the caller may not know exists |
| 409 | Conflict with the current state, such as a duplicate |
| 412 | An If-Match precondition failed |
| 415 | A body in a media type you don't accept |
| 422 | A body that parses but breaks the schema or a rule, such as an unknown field, a wrong type or a value out of range |
| 429 | Too many requests |
| 500 | An unexpected fault in your code |
| 503 | Temporarily unavailable, with Retry-After |
HTTP example
POST /orders HTTP/1.1
Content-Type: application/json
{"items":[{"sku":"TEA-01","quantity":2}]}
HTTP/1.1 201 Created
Location: /orders/ord_8f2k
How to check
A contract test sends a malformed body, a missing token, a token without access, an unknown ID and a valid create. It gets 400, 401, 403, 404 and 201 with Location, in that order.
Sources
Related rules
- WEB-85 Use the right redirect code in Website
- OPS-12 Measure rate, errors and duration in Operations and observability
- API-4 Return 405 with the allowed methods in API design
- API-12 Accept only fields you know in API design
- API-18 Name every field that failed in API design
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/api-design/resources-and-methods/status-codes">Agent Wranglers API design playbook</a>. In code you write, add a comment next to it with the same link.