Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 39 ยท HTTP and REST Fundamentals

HTTP Status Codes for APIs

Learn which HTTP status code to return from a REST API: 2xx success, 3xx redirects, 4xx client errors and 5xx server errors, with a decision guide and runnable examples.

A status code is the first thing a client reads in a response, and often the only thing it needs. A client that gets 201 knows the resource was created, 404 means it does not exist, 429 means slow down. Good APIs use status codes precisely so that generic tools (retry logic, monitors, caches, browsers) can react without parsing the body.

Codes are grouped by their first digit. Learn the five families, then the dozen codes that cover almost every API.

The five families

Status code families

1xx Informational Rarely used by API code.
2xx Success The request worked.
3xx Redirection Look somewhere else, or use your cache.
1 / 2

The most useful rule: 4xx means "your request is the problem, do not retry unchanged"; 5xx means "our problem, a retry later may work". Monitoring dashboards alert on 5xx rates, so wrongly returning 500 for bad user input pollutes your alerts.

Success: 2xx

Code Name Use it when
200 OK A read or update succeeded and the response has a body
201 Created A POST (or PUT) created a resource. Include a Location header
202 Accepted The request was accepted but work happens later (background job)
204 No Content Success with nothing to return, typically DELETE or a PUT that echoes nothing

Do not return 200 with {"success": false} for a failure. That breaks every tool that trusts the status code.

Redirection and caching: 3xx

Code Meaning
301 / 308 Moved permanently (308 keeps the method)
302 / 307 Moved temporarily (307 keeps the method)
304 Not Modified: the cached copy is still valid (see headers)

Client errors: 4xx

Code Name Typical API use
400 Bad Request Malformed syntax, invalid JSON, missing required parameter
401 Unauthorized Not authenticated: no or invalid credentials. Send WWW-Authenticate
403 Forbidden Authenticated, but not allowed to do this
404 Not Found No such resource (also used to hide that a resource exists)
405 Method Not Allowed URL exists, method does not. Send Allow
406 Not Acceptable Cannot produce any format the client's Accept allows
409 Conflict State conflict: duplicate email, edit of an outdated version
410 Gone Existed once, removed on purpose
413 Content Too Large Body exceeds your limit
415 Unsupported Media Type Body Content-Type not supported
422 Unprocessable Content Syntax is fine but values fail validation rules
429 Too Many Requests Rate limit hit. Send Retry-After

Two pairs cause constant confusion:

  • 401 vs 403. 401 is about who you are (despite its name, "Unauthorized"). 403 is about what you may do. A logged-in user who edits someone else's order gets 403. See authentication vs authorization.
  • 400 vs 422. Teams differ here. A common rule: 400 when the request cannot be parsed or is structurally wrong (broken JSON, wrong type for a parameter), 422 when it parses fine but breaks business or validation rules (an email without @, a negative quantity). Pick one convention and document it. Both are acceptable; being consistent matters more.

Server errors: 5xx

Code Name Use it when
500 Internal Server Error Unexpected bug. Hide details from the client
502 Bad Gateway A gateway got an invalid answer from an upstream service
503 Service Unavailable Overloaded or down for maintenance. Send Retry-After
504 Gateway Timeout An upstream service did not answer in time

A decision guide

flowchart TD
    A["Request arrives"] --> B{"Understandable? valid JSON, known route"}
    B -- No --> C["400 / 404 / 405 / 415"]
    B -- Yes --> D{"Authenticated?"}
    D -- No --> E["401"]
    D -- Yes --> F{"Allowed?"}
    F -- No --> G["403 or 404"]
    F -- Yes --> H{"Valid and consistent?"}
    H -- No --> I["422 / 409"]
    H -- Yes --> J{"Server bug?"}
    J -- Yes --> K["500"]
    J -- No --> L["200 / 201 / 204"]

Check in this order: parse, authenticate, authorize, validate, execute.

Status codes in action

The server below answers the same kind of request with different codes. The client prints each result along with the family it belongs to.

Node.js A tour of status codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the extra headers: Location with 201 and 308, WWW-Authenticate with 401, Retry-After with 429 and 503. A status code often comes with a header that completes its meaning.

Choosing between 400, 409 and 422

This POST /users handler shows the difference between a broken request, a rule violation and a conflict with existing data.

Node.js 400, 422 and 409 on POST /users

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A logged-in user tries to delete another user's account without permission. Which status fits best?

    The user is authenticated, but not allowed. 401 is for missing or invalid credentials. (Some APIs use 404 to hide that the account exists.)
  2. 2. Which status code should a successful POST that creates a resource return?

    201 Created, usually with a Location header pointing at the new resource.
  3. 3. Why is returning 200 with {"success": false} a bad idea?

    Tooling trusts the status code. Use a proper 4xx or 5xx code for errors.
  4. 4. What does 5xx tell a client, compared with 4xx?

    4xx points to the request, 5xx to the server. Retrying unchanged is only sensible for 5xx (and some 429 cases after waiting).
  5. 5. A signup request uses an email that is already registered. Which code is the most precise?

    409 signals a conflict with the current state of the server's data.

Summary

  • Families: 2xx success, 3xx redirect or cache, 4xx client error, 5xx server error.
  • Use 201 + Location for creation, 204 for empty success, 202 for accepted background work.
  • 401 means not authenticated, 403 means not allowed, 404 not found, 405 wrong method, 409 conflict, 422 validation failure, 429 rate limit.
  • Never return 200 for failures, and never leak details in 500 responses.
  • Check in order: parse, authenticate, authorize, validate, execute.

Next: Headers and Content Negotiation