WEB API's Lesson 7 – HTTP Status Codes | Dataplexa
Web APIs · Lesson 7

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.

Client Errors (4xx)
The request contains a problem. Check your data, headers, or permissions before retrying.
Server Errors (5xx)
The server failed to process a valid request. Usually safe to retry after a delay.
The 4xx family indicates client errors. When you send malformed JSON to an API, expect 400 Bad Request. When you access a protected resource without authentication, expect 401 Unauthorized. These errors mean your request needs fixing.

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.

The APIForge Backend team uses 201 for all resource creation endpoints, 200 for data retrieval and updates that return content, and 204 for successful deletions. This pattern makes client-side success handling predictable across their entire platform.
202 Accepted handles asynchronous operations. When processing takes time – like generating reports or processing uploaded files – the server returns 202 to acknowledge the request without waiting for completion. The response typically includes information about checking operation status later.

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
404 Not Found is the most recognizable status code. It means the requested resource doesn't exist at the specified URL. This could indicate a typo in the endpoint path, a deleted resource, or an outdated API reference.

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.

Retry Strategy
For 5xx errors, implement exponential backoff: retry after 1 second, then 2, then 4, then 8. For 4xx errors, fix the request instead of retrying – the same request will fail again.
504 Gateway Timeout happens when proxy servers don't receive timely responses from backend services. Long-running database queries or external API calls that exceed timeout limits cause 504 errors. This suggests performance optimization needs rather than simple bugs.

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.

Poor Status Code Usage
Returns 200 OK for all requests
Error details buried in response body
Client must parse content to detect failures
Proper Status Code Usage
Status code indicates outcome immediately
Response body provides additional context
Client can handle errors without parsing content
Consider how Stripe's payment API uses status codes. Successful charges return 201 Created. Declined cards return 402 Payment Required. Invalid card numbers return 400 Bad Request. Each status code enables specific client-side handling without examining response content.

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 Best Practice
Stick to standard HTTP status codes unless you have compelling reasons for extensions. Standard codes work predictably with all HTTP tooling and client libraries.
The APIForge Product team researched using custom 2xx codes for different types of successful operations. They discovered that monitoring tools flagged unknown codes as potential errors, causing false alerts. They reverted to standard codes with detailed response bodies for operation-specific information.

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.

1
Send Valid Request
POST user creation data with all required fields properly formatted
2
Verify Success Status
Response should return 201 Created, not 200 OK or other success codes
3
Test Error Conditions
Repeat request with duplicate email to verify 409 Conflict response
4
Validate Error Details
Confirm error responses include helpful messages in response body
The APIForge DevOps team builds automated tests that verify status codes match response content. Tests that expect 201 responses also verify the response contains newly created resource data. Tests that expect 404 responses verify empty or error-specific response bodies.

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.

Documentation Warning
Never document status codes your API doesn't actually return. Outdated documentation that promises 409 Conflict responses when your API returns 400 Bad Request breaks client error handling.
GitHub's API documentation exemplifies excellent status code coverage. Each endpoint shows possible status codes with example responses and explanations. Their webhook documentation includes status codes for different failure types, enabling robust event processing.

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?

Up Next
Request and Response
APIForge explores the anatomy of HTTP messages that carry data between clients and servers.