HTTP Status Code Selection
Choosing semantically correct HTTP status codes so clients can programmatically handle success, client errors, and server errors.
Description
HTTP status codes are a three-digit classification system that tells API consumers whether a request succeeded, failed due to client error, or failed due to a server-side issue. Selecting the right code is critical because automated clients, proxies, and CDNs make routing and retry decisions based on these codes. Using 200 for everything and embedding error information only in the body defeats the purpose of HTTP semantics and breaks standard middleware behavior.
The main categories are 2xx for success (200 OK, 201 Created, 202 Accepted, 204 No Content), 3xx for redirections, 4xx for client errors (400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict, 422 Unprocessable Entity, 429 Too Many Requests), and 5xx for server errors (500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable). Each code carries specific semantics -- for example, 401 means the request lacks valid authentication credentials, while 403 means the authenticated user lacks permission.
Consistent status code usage enables clients to implement robust error-handling logic. A client can automatically retry on 503, prompt re-authentication on 401, and display validation errors on 422, all without parsing the response body first. Teams should document their status code usage in their API style guide and validate it in integration tests.
Prompt Snippet
Return 200 for successful GET/PUT/PATCH, 201 with Location header for POST that creates a resource, 202 for async operations accepted for processing, and 204 for successful DELETE. Use 400 for malformed request syntax, 401 when no valid Bearer token is present, 403 for authenticated but unauthorized access, 404 for nonexistent resources, 409 for state conflicts (e.g., duplicate creation), 422 for schema-valid but semantically invalid input (e.g., end_date before start_date), and 429 with Retry-After header for rate-limited requests.
Tags
Related Terms
REST API Conventions
A set of architectural constraints and naming conventions for designing consistent, predictable HTTP APIs around resources.
API Error Response Format
A standardized structure for error responses that includes machine-readable error codes, human-readable messages, and field-level details.
API Rate Limiting
Restricting the number of API requests a client can make within a time window to protect backend resources and ensure fair usage.