How does an API typically use HTTP status codes to communicate the result of a request, and what do common codes like 200, 404, and 500 represent?
Short answer
HTTP status codes provide a standardized way for an API to communicate the outcome of a request, with codes in the 200 range indicating success, such as 200 for a successful GET request or 201 specifically for a successful resource creation, codes in the 400 range indicating a…
Advertisement
AModel answer
HTTP status codes provide a standardized way for an API to communicate the outcome of a request, with codes in the 200 range indicating success, such as 200 for a successful GET request or 201 specifically for a successful resource creation, codes in the 400 range indicating a client error, such as 404 for a resource that does not exist or 400 for a malformed request, and codes in the 500 range indicating a server side error, giving API consumers a reliable, consistent way to programmatically determine what happened without needing to parse the response body just to know if something succeeded or failed.
http_response_code(404);
echo json_encode(['error' => 'Product not found']);Real-world example
An API correctly returns a 404 status code along with a clear error message when a requested product identifier does not exist, letting the client application easily detect and handle this specific situation using the status code alone.
Likely follow-ups
- What is the difference between a 401 and a 403 status code?
- Why is it considered bad practice to always return a 200 status code even when an error actually occurred?
Related topics