HTTP Error Codes
1. Introduction
HTTP error codes are a critical part of REST APIs, providing clients with valuable information about what went wrong when a request fails. Error codes help developers troubleshoot issues, guide them in correcting their requests, and improve the overall robustness and usability of the API. This chapter covers the most common HTTP error codes, explains their meanings, and offers best practices for using them effectively in your REST APIs.
2. Understanding HTTP Status Codes
HTTP status codes are three-digit numbers returned by the server in response to a client’s request. These codes are grouped into five classes based on their first digit:
- 1xx (Informational): Request received, continuing process.
- 2xx (Success): Request successfully received, understood, and accepted.
- 3xx (Redirection): Further action needs to be taken to complete the request.
- 4xx (Client Error): The request contains incorrect syntax or cannot be fulfilled.
- 5xx (Server Error): The server failed to fulfill a valid request.
This chapter focuses primarily on 4xx and 5xx codes, which indicate errors that developers need to address.
3. Common 4xx Client Error Codes
-
400 Bad Request
- Meaning: The server cannot or will not process the request due to something perceived as a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
- When to Use: Use this code when the client sends invalid data, such as missing required fields, invalid JSON format, or incorrect query parameters.
- Example Use Case:
- A request to create a user is missing the required
emailfield:POST /users.
- A request to create a user is missing the required
-
401 Unauthorized
- Meaning: The client must authenticate itself to get the requested response. This status code indicates that the request lacks valid authentication credentials.
- When to Use: Use this code when the request requires authentication but the client has not provided it or provided invalid credentials.
- Example Use Case:
- A request to access a protected resource without a valid token:
GET /protected-data.
- A request to access a protected resource without a valid token:
-
403 Forbidden
- Meaning: The server understands the request but refuses to authorize it. Unlike 401, authentication does not help, and the request should not be repeated.
- When to Use: Use this code when the client’s credentials are valid, but they do not have permission to access the resource.
- Example Use Case:
- A user attempts to delete a resource they do not own:
DELETE /users/123.
- A user attempts to delete a resource they do not own:
-
404 Not Found
- Meaning: The server cannot find the requested resource. This status code indicates that the endpoint is valid, but the resource itself does not exist.
- When to Use: Use this code when a client tries to access a non-existent resource.
- Example Use Case:
- A request for a user with a non-existent ID:
GET /users/999.
- A request for a user with a non-existent ID:
-
405 Method Not Allowed
- Meaning: The method specified in the request is not allowed for the resource identified by the request URI.
- When to Use: Use this code when the HTTP method used is not supported by the endpoint.
- Example Use Case:
- A request to update a resource using GET instead of PUT:
GET /users/123.
- A request to update a resource using GET instead of PUT:
-
409 Conflict
- Meaning: The request could not be completed due to a conflict with the current state of the target resource.
- When to Use: Use this code when a request would cause a conflict, such as creating a duplicate resource.
- Example Use Case:
- Attempting to create a user with an email address that already exists:
POST /users.
- Attempting to create a user with an email address that already exists:
-
422 Unprocessable Entity
- Meaning: The server understands the content type of the request entity, and the syntax is correct, but it was unable to process the contained instructions.
- When to Use: Use this code when the request is syntactically correct, but semantically invalid (e.g., business logic validation fails).
- Example Use Case:
- Submitting a form with valid syntax but invalid business rules, such as an age below the allowed minimum:
POST /registrations.
- Submitting a form with valid syntax but invalid business rules, such as an age below the allowed minimum:
-
429 Too Many Requests
- Meaning: The client has sent too many requests in a given amount of time (“rate limiting”).
- When to Use: Use this code to indicate that the client has hit the rate limit and should try again later.
- Example Use Case:
- A client repeatedly sending requests faster than allowed:
GET /data.
- A client repeatedly sending requests faster than allowed:
4. Common 5xx Server Error Codes
-
500 Internal Server Error
- Meaning: The server encountered an unexpected condition that prevented it from fulfilling the request.
- When to Use: Use this code when an unexpected error occurs on the server, often due to programming errors or unexpected conditions.
- Example Use Case:
- A database connection fails during a request:
GET /users.
- A database connection fails during a request:
-
501 Not Implemented
- Meaning: The server does not support the functionality required to fulfill the request.
- When to Use: Use this code when the server lacks the capability to perform the requested method or functionality.
- Example Use Case:
- A client tries to use a method that the server does not support:
PATCH /users/123.
- A client tries to use a method that the server does not support:
-
502 Bad Gateway
- Meaning: The server, while acting as a gateway or proxy, received an invalid response from the upstream server.
- When to Use: Use this code when the server is acting as a gateway and receives an error from the upstream service.
- Example Use Case:
- A load balancer receives an invalid response from the backend service.
-
503 Service Unavailable
- Meaning: The server is currently unable to handle the request due to temporary overloading or maintenance of the server.
- When to Use: Use this code when the server is temporarily down for maintenance or overloaded.
- Example Use Case:
- Scheduled maintenance downtime:
GET /service-status.
- Scheduled maintenance downtime:
-
504 Gateway Timeout
- Meaning: The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server.
- When to Use: Use this code when the server times out while waiting for a response from another server.
- Example Use Case:
- A timeout occurs when a request to an external API takes too long:
GET /external-data.
- A timeout occurs when a request to an external API takes too long:
5. Best Practices for Using HTTP Error Codes
-
Be Specific: Use the most appropriate error code to convey the exact nature of the error. Avoid using generic codes like 500 for all failures, as they provide little information to the client.
-
Provide Meaningful Error Messages: Include a descriptive error message in the response body to help clients understand the cause of the error and how to resolve it.
-
Consistent Error Structure: Maintain a consistent error response format across your API, typically including an error code, message, and any relevant details or suggestions.
-
Secure Error Handling: Avoid exposing sensitive information in error responses, such as stack traces or internal implementation details, which could be exploited by attackers.
-
Rate Limiting and Throttling: Use 429 Too Many Requests to handle excessive client requests gracefully and guide users on when they can try again.
-
Graceful Degradation: For planned outages or maintenance, use 503 Service Unavailable to inform clients of temporary unavailability.
6. Conclusion
HTTP error codes are essential tools for communicating issues between the client and server, helping developers diagnose problems and improve the robustness of APIs. By using the right error codes and following best practices, you can enhance the usability, security, and maintainability of your RESTful APIs, ensuring a smoother and more predictable experience for your users.