APIs
2 min read
Use HTTP Status Codes to Help API Clients Recover
Choose HTTP status codes and response details that help API clients retry, correct input, authenticate, and diagnose failures safely.
An HTTP status code is a compact signal about what happened to a request and what a client should do next. It is most useful when it matches the response body, logs, and retry policy. A generic 500 for every failure makes clients blind; an overly detailed error can expose internals or personal data. Good API errors are specific enough to recover and restrained enough to protect the system.
## Separate client, auth, and server failures
Use 400-level responses when the client can change the request: malformed input, missing fields, invalid credentials, or insufficient permission. Use 500-level responses when the service failed despite a valid request. A 401 generally means authentication is required or failed, while 403 means the identity is known but lacks permission. Keep your own API conventions documented and consistent.
The CalcSnippets HTTP Status Code Lookup offers a quick reminder of common meanings and next steps. It should not replace the API's own error contract. Clients need stable machine-readable fields such as an error code, safe message, correlation id, and validation details where appropriate.
## Make retries evidence-based
Not every failure should be retried. A malformed request will not improve with repetition. A timeout, 429, or temporary 503 may be retryable with backoff and a limit. For write operations, use idempotency keys or another design that prevents a retry from creating duplicate work. Include `Retry-After` when the service can provide a meaningful wait period.
Log the underlying exception with a correlation id, but do not send stack traces or secret values to the client. Verify error handling with integration tests that cover validation, authentication, conflicts, throttling, and dependency outages. Clear status codes and honest recovery instructions reduce support load because clients can respond correctly without guessing.