Web APIs
HTTP Status Codes
Decode the three-digit messages that tell you exactly what happened with every API request.
When Netflix's API returns a 404 because a movie vanished from their catalog, or Stripe sends back 201 after successfully charging a credit card, those numbers mean everything. HTTP status codes are the universal language servers use to communicate success, failure, and everything in between to client applications.Every HTTP response carries a three-digit status code that instantly tells your application what happened. No parsing response bodies. No guessing. The status code communicates the outcome before you read a single byte of data.
Status codes follow a strict pattern. The first digit defines the category. The remaining two digits specify the exact situation. This system lets developers write robust error handling without memorizing hundreds of specific codes.
The Five Status Code Families
Status codes group into five families, each covering a different type of server response.The 1xx family handles informational messages. These codes rarely appear in typical API work because they communicate protocol-level information like "continue sending your request" or "switching protocols." Most REST APIs skip straight to definitive responses.
The 2xx family signals success. When GitHub's API creates a new repository, it returns 201 Created. When Slack's API fetches your channel list, it returns 200 OK. Every successful operation maps to a specific 2xx code.
The 3xx family handles redirections. If an API endpoint moved to a new URL, the server returns 301 Moved Permanently with the new location. Your HTTP client can automatically follow the redirect and complete the request.
The 5xx family covers server errors. Database crashes, service outages, and internal bugs trigger 5xx responses. Unlike 4xx errors, 5xx codes usually mean the same request might succeed later when the server recovers.
Success Codes That Matter
Success codes do more than just say "it worked" – they communicate exactly what the server accomplished.200 OK is the workhorse of successful responses. GET requests return 200 when they fetch data successfully. PUT requests return 200 when they update existing resources. Any operation that succeeds and returns data typically uses 200.
201 Created specifically indicates successful resource creation. When you POST data to create a new user account, the API should return 201 along with the newly created user object. This distinction helps client applications understand whether they triggered creation or retrieval.
204 No Content confirms successful operations that return no data. DELETE requests often use 204 because deleting a resource leaves nothing to return. Some PUT requests use 204 when updating a resource without returning the updated version.
Client Error Patterns
Client errors reveal specific problems with requests, enabling precise error handling and user feedback.400 Bad Request covers malformed requests. Invalid JSON syntax, missing required fields, or data that fails validation all trigger 400 responses. The response body typically contains details about what went wrong.
401 Unauthorized means authentication failed or is missing. Despite the name, 401 specifically indicates authentication problems – not authorization issues. When an API requires a valid API key and receives none, it returns 401.
403 Forbidden indicates authorization failures. The server understood your credentials but determined you lack permission for the requested operation. A regular user trying to access admin-only endpoints receives 403.
| Status Code | Meaning | Common Cause |
|---|---|---|
| 404 Not Found | Resource doesn't exist | Wrong endpoint URL or deleted resource |
| 405 Method Not Allowed | HTTP method not supported | POSTing to a GET-only endpoint |
| 422 Unprocessable Entity | Valid JSON, invalid data | Email format incorrect, password too short |
| 429 Too Many Requests | Rate limit exceeded | Making requests faster than allowed |
422 Unprocessable Entity distinguishes between syntax errors (400) and semantic errors. The request contains valid JSON with proper structure, but the data itself violates business rules. An email field containing "not-an-email" triggers 422, not 400.
Server Error Recovery
Server errors indicate problems beyond client control, but different 5xx codes suggest different response strategies.500 Internal Server Error is the generic server failure response. Application crashes, unhandled exceptions, or database connection failures often result in 500 errors. These typically resolve with server restarts or bug fixes.
502 Bad Gateway occurs when a proxy server receives invalid responses from upstream servers. Load balancers return 502 when backend servers crash or become unreachable. This often indicates infrastructure problems rather than application bugs.
503 Service Unavailable means the server temporarily cannot handle requests. Planned maintenance, resource exhaustion, or overload conditions trigger 503 responses. The response may include a Retry-After header indicating when to try again.
Status Codes in Practice
Real applications need consistent status code patterns to enable effective error handling and user experiences.The APIForge Security team builds authentication middleware that returns precise status codes based on failure types. Missing API keys trigger 401. Expired tokens trigger 401. Valid tokens accessing forbidden resources trigger 403. This precision helps client applications show appropriate error messages.
Their user registration endpoint demonstrates proper status code usage. Valid registration data returns 201 with the new user object. Duplicate email addresses return 409 Conflict with error details. Malformed email formats return 422 with validation messages.
Twitter's API rate limiting demonstrates 429 Too Many Requests effectively. The response includes headers showing remaining request quota and reset time. Client applications can automatically pause requests until the rate limit resets.
Custom Status Codes and Standards
While HTTP defines standard status codes, some scenarios benefit from custom codes within the defined ranges.WebDAV extends HTTP with additional status codes like 207 Multi-Status for operations affecting multiple resources. Some APIs adopt these extended codes when they provide clearer communication than standard alternatives.
Microsoft and other vendors introduced codes like 451 Unavailable For Legal Reasons for content blocked by legal requirements. These extensions follow RFC processes and maintain compatibility with standard HTTP parsing.
However, creating truly custom status codes breaks client expectations. HTTP libraries, monitoring tools, and debugging utilities expect standard codes. Custom codes may not trigger appropriate client-side error handling or logging.
Status Code Testing Strategy
Comprehensive API testing requires verifying correct status codes for both success and failure scenarios.Test happy path scenarios first. Verify that valid requests return appropriate 2xx codes with expected response bodies. User creation should return 201. Data retrieval should return 200. Successful deletion should return 204.
Test client error conditions systematically. Send requests with missing required fields and verify 400 responses. Access protected endpoints without authentication and verify 401 responses. Use valid credentials to access forbidden resources and verify 403 responses.
Test edge cases that reveal status code logic bugs. Send syntactically valid JSON with semantically invalid data to distinguish between 400 and 422 responses. Test rate limiting to verify proper 429 handling with appropriate headers.
Load testing reveals status code behavior under stress. Overloaded servers should return 503 Service Unavailable rather than crashing silently. Rate-limited endpoints should return 429 Too Many Requests with proper retry guidance.
Status Code Documentation
Clear documentation helps API consumers understand and handle status codes appropriately.Document all possible status codes for each endpoint. Include not just success scenarios, but also authentication failures, validation errors, and server problems. Comprehensive status code documentation prevents client-side surprises.
Provide example responses for each status code. Show both the status code and typical response body content. This helps developers understand what additional information accompanies each status code.
Explain retry policies for different error types. Document which errors indicate temporary failures suitable for retry and which indicate permanent failures requiring request changes. Include recommended retry delays and maximum retry attempts.
OpenAPI specifications enable machine-readable status code documentation. Tools can generate client libraries with proper error handling based on documented status codes. This automation reduces integration bugs and development time.
Status codes transform HTTP from a simple request-response protocol into a rich communication system. They enable robust error handling, improve debugging efficiency, and create predictable client experiences. Mastering status codes means building APIs that communicate clearly with both humans and machines.The difference between a professional API and an amateur one often comes down to status code precision. Professional APIs return exactly the right status code for each situation, enabling clients to respond appropriately. Amateur APIs return generic codes that force clients to guess what really happened.
Quiz
1. The APIForge Backend team needs to return a status code when their database is temporarily overloaded during peak traffic. What should they use?
2. A user registration endpoint receives valid JSON with proper structure, but the email field contains "invalid-email-format". What status code should it return?
3. The APIForge Frontend team successfully creates a new project through the API and receives the new project object in the response. What status code should they expect?