HTTP status codes are essential for communicating the result of an API request. They provide information about whether a request was successful, if there were errors, or if further action is needed. Correctly implementing these codes is crucial for a smooth API experience. Here are three practical examples of using HTTP status codes correctly in APIs.
In this scenario, an API is designed to create a new user account. When the account is successfully created, a 201 Created
status code is returned, along with the details of the newly created user.
When a client sends a POST request to the /users
endpoint, the server processes the request and creates a user in the database. If everything goes smoothly, the server responds as follows:
POST /users HTTP/1.1
Content-Type: application/json
{
"username": "new_user",
"email": "new_user@example.com"
}
Response:
HTTP/1.1 201 Created
Content-Type: application/json
{
"id": "12345",
"username": "new_user",
"email": "new_user@example.com"
}
This response indicates that the user was successfully created, and the client can use the user ID for further requests.
Location
header for better navigation.400 Bad Request
status instead.In this use case, a client is trying to retrieve a specific user by their ID. If the user does not exist in the system, the API should return a 404 Not Found
status code to inform the client of the issue.
When a GET request is sent to the /users/99999
endpoint, where 99999
does not correspond to any existing user, the server responds:
GET /users/99999 HTTP/1.1
Response:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": "User not found"
}
This clearly indicates to the client that the requested resource could not be found.
404
errors to help identify potential issues with client requests.In this scenario, an API endpoint requires authentication to access user data. If a client tries to access this endpoint without providing valid credentials, the server should return a 401 Unauthorized
status code.
When a client sends a GET request to the /users/me
endpoint without a token:
GET /users/me HTTP/1.1
Authorization: Bearer
Response:
HTTP/1.1 401 Unauthorized
Content-Type: application/json
{
"error": "Access denied. Please provide a valid token."
}
This response informs the client that they need to authenticate before they can access the requested resource.
WWW-Authenticate
header to indicate how clients can authenticate (e.g., via a Bearer token).403 Forbidden
status code instead, as the client may need to refresh their token.