HTTP Status Codes · Tutorial

How to choose the right HTTP status codes for an API

8 min readintermediateUpdated

You are designing a small JSON API and every error currently returns 500 or 200 with an error message inside. This tutorial walks through common situations, looks up each code in the reference, and ends with a table you can follow.

What you need

  • The HTTP Status Codes reference
  • A list of your API’s endpoints and the ways they can fail

Steps

  1. Use 2xx for real success only

    Return 200 OK with data for reads, 201 Created with a Location header after creating a record, and 204 No Content after a delete. Never send 200 with an error message inside; clients and monitoring tools rely on the code.

  2. Separate bad input from invalid data

    Search for 400 and 422. Use 400 Bad Request when the body can’t be parsed, such as broken JSON, and 422 Unprocessable Content when it parses but fails validation, like an invalid email. Return the field errors in the body.

  3. Distinguish 401, 403 and 404

    401 means no valid credentials, so the client should sign in. 403 means signed in but not allowed. 404 means the record doesn’t exist. Some APIs return 404 instead of 403 to avoid revealing that a private record exists.

  4. Handle conflicts and limits

    Use 409 Conflict for duplicates or edit conflicts, and 429 Too Many Requests for rate limiting. The sample search jumps straight to 429; its tip reminds you to send a Retry-After header.

    HTTP/1.1 429 Too Many Requests
    Retry-After: 30
    Content-Type: application/json
    
    {"error": "rate_limited", "retryAfterSeconds": 30}
  5. Keep 5xx for real server failures

    500 is for bugs and unexpected failures, 503 for planned maintenance or overload with Retry-After, and 502 or 504 come from proxies when your application is down or too slow. Clients may retry 5xx responses automatically, so don’t use them for bad input.

  6. Write it down

    Add a short table to your API documentation listing the codes each endpoint returns, so client developers can handle every case.

Try it yourself

Opens the HTTP Status Codes with this tutorial's sample loaded.

Try it now

Common mistakes

Returning 200 for errors
Monitoring, caching and retry logic all read the status code. An error with 200 looks like success to every tool.
Using 403 for not signed in
If the client could fix it by signing in, it is 401, and the response should include a WWW-Authenticate header.
Retrying 4xx errors
Repeating a request with bad input gives the same result. Retry 429 and 503 after waiting, not 400 or 422.

Next steps

Go back to the HTTP Status Codes, or keep going with one of these:

FAQ

Is 422 or 400 more common for validation errors?

Both are widely used. 422 is more specific; whichever you pick, use it consistently.

Should a search with no results return 404?

No. An empty result is still a successful search: return 200 with an empty list.