REST API Status Codes: 12 HTTP Codes Every Backend Developer Should Use Right

REST API status codes: 12 HTTP codes every backend developer should use right

Introduction

Every API response starts with a three-digit number. That number tells the client what happened before it reads a single line of the body. When the status code is right, clients can retry safely, show clear errors, and alert the right people. When it is wrong, a failed request looks like a success, and bugs hide for weeks.

We see this often when we take over existing APIs. An endpoint returns 200 OK with an error inside the body. A typo in the input returns 500. A client that is not logged in gets 403 instead of 401. Each mistake is small, but together they make an API hard to trust.

In this guide, we cover the 12 REST API status codes that matter most, when to use each one, and the common mistakes to avoid. The examples are simple HTTP responses, so you can use them in any language: PHP, Node.js, Python, Go, or Java.

Why REST API Status Codes Matter

Status codes are a contract between your API and everyone who uses it. Client libraries, API gateways, load balancers, and monitoring tools all read the status code first. Many of them never look at the body.

  • Retries depend on them. Clients usually retry 429 and 503 errors, and never retry 400 or 422. A wrong code can cause duplicate actions or lost requests.
  • Monitoring depends on them. Dashboards count 5xx responses as server errors. If you return 200 for failures, your error rate looks perfect while customers suffer.
  • Debugging depends on them. A clear 4xx code tells the developer the problem is in their request, not in your server.
  • Billing can depend on them. If a send fails but returns 200, a customer may be charged for something that never happened.

The Five Status Code Classes

Every status code belongs to one of five groups. The first digit tells you which group:

ClassMeaningWho should act
1xxInformationalRarely used in REST APIs
2xxSuccessNothing to do
3xxRedirectionClient follows the new location
4xxClient errorThe caller must fix the request
5xxServer errorThe API team must fix the server

12 REST API Status Codes with Examples

1. 200 OK: The request worked and the response has a body.

Use it for successful GET requests and for updates that return the changed resource. Do not use 200 when something failed. A body like {"status": "error"} with a 200 code confuses every client and monitoring tool.

HTTP/1.1 200 OK
Content-Type: application/json

{"id": 42, "name": "Asha", "plan": "pro"}

2. 201 Created: A new resource was created.

Return 201 after a successful POST that creates something. Add a Location header that points to the new resource, so the client knows where to find it.

HTTP/1.1 201 Created
Location: /v1/messages/9182
Content-Type: application/json

{"id": 9182, "status": "queued"}

3. 204 No Content: Success, with nothing to return.

Use 204 for a successful DELETE, or an update where the client does not need the result. Do not send a body with 204. If the work will happen later, for example a message that is queued for sending, use 202 Accepted instead.

4. 400 Bad Request: The request itself is broken.

Use 400 for JSON that will not parse, a missing required header, or a value of the wrong type. It tells the client: fix the request before you try again.

5. 401 Unauthorized: We do not know who you are.

Despite the name, 401 means not authenticated. The API key or token is missing, expired, or wrong. Include a WWW-Authenticate header when you can.

6. 403 Forbidden: We know who you are, but you cannot do this.

The user is logged in but does not have permission. For example, a normal user tries to delete another account’s data. Retrying with the same credentials will not help.

7. 404 Not Found: The resource does not exist.

Return 404 for an unknown ID or path. For private data, many APIs return 404 instead of 403, so attackers cannot learn which IDs exist.

8. 409 Conflict: The request clashes with the current state.

Use 409 for a duplicate username, a version conflict during an update, or a second request that is still running with the same idempotency key.

9. 422 Unprocessable Content: The request is well formed, but the data is invalid.

The JSON parsed fine, but a phone number is not valid or an end date comes before a start date. Many teams use 422 for validation errors and 400 for broken requests. Pick one rule and use it everywhere.

HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json

{
  "type": "https://api.example.com/errors/validation",
  "title": "Invalid request data",
  "status": 422,
  "errors": [
    {"field": "to", "message": "Must be a valid E.164 phone number"}
  ]
}

10. 429 Too Many Requests: Slow down.

Return 429 when a client goes over its rate limit. Always add a Retry-After header, so well-behaved clients know how long to wait.

HTTP/1.1 429 Too Many Requests
Retry-After: 30

11. 500 Internal Server Error: Something broke on our side.

500 should mean a bug or an unexpected failure. It should never be the answer to bad user input. Log the details on the server, and return a short, safe message. Never send stack traces or SQL errors to the client.

12. 503 Service Unavailable: We cannot take this request right now.

Use 503 during maintenance, when a queue or database is down, or when the system is overloaded. It tells the client the problem is temporary. Add Retry-After if you know when you will be back.

Setting Status Codes in PHP

Most frameworks set the status code for you. In plain PHP, use http_response_code() before you send the body:

<?php
function jsonResponse(int $status, array $data): void
{
    http_response_code($status);
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}

if (!isset($_POST['to'])) {
    jsonResponse(422, ['error' => 'The "to" field is required']);
}

$id = createMessage($_POST);
header("Location: /v1/messages/{$id}");
jsonResponse(201, ['id' => $id, 'status' => 'queued']);

Quick Reference Table

SituationStatus code
Read data successfully200 OK
Created a new resource201 Created
Accepted for later processing202 Accepted
Deleted, nothing to return204 No Content
Malformed JSON or wrong type400 Bad Request
Missing or bad API key401 Unauthorized
Logged in, but not allowed403 Forbidden
Unknown ID or path404 Not Found
Duplicate or version conflict409 Conflict
Valid JSON, invalid data422 Unprocessable Content
Rate limit exceeded429 Too Many Requests
Unexpected bug500 Internal Server Error
Overloaded or in maintenance503 Service Unavailable

Common Status Code Mistakes to Avoid

  • Returning 200 for errors. If the request failed, use a 4xx or 5xx code, even if the body explains the error.
  • Returning 500 for bad input. Validate input first, and return 400 or 422. Save 500 for real server bugs.
  • Mixing up 401 and 403. 401 means “who are you?”. 403 means “you cannot do this”.
  • Forgetting Retry-After. Without it, clients retry 429 and 503 errors too fast and make the overload worse.
  • Leaking internals. Error bodies should never include SQL queries, file paths, or stack traces.
  • Inconsistent error bodies. Use one error format for every endpoint. The application/problem+json format from RFC 9457 is a good standard to follow.

Conclusion

Good status codes cost nothing to add, but they make an API much easier to use. Start with the 12 codes in this guide, pick one clear error format, and test your error paths as carefully as your happy paths. Your clients, your monitoring, and your support team will all thank you.

FAQs

1. What is the difference between 401 and 403?

401 Unauthorized means the client is not authenticated: the token is missing, wrong, or expired. 403 Forbidden means the client is authenticated but does not have permission for this action.

2. Should I use 400 or 422 for validation errors?

Both are common. A simple rule is: 400 for requests that cannot be parsed, and 422 for well-formed requests with invalid values. What matters most is using the same rule across your whole API.

3. Is it okay to return 200 with an error message in the body?

No. Clients, gateways, and monitoring tools trust the status code. A 200 with an error inside hides failures and breaks retry logic.

4. When should I use 202 instead of 201?

Use 201 when the resource is created right away. Use 202 when you have accepted the request but the work will finish later, such as a message placed in a queue.

5. Which status codes should a client retry?

Usually 429, 502, 503, and 504, after waiting. Do not retry 4xx errors like 400, 401, 403, 404, or 422 without changing the request.

Official Documentation

Talk to Our API Experts

Unclear errors and wrong status codes make an API hard to integrate and hard to support. At Pheonix Solutions, our backend team designs, builds, and fixes REST APIs that clients can trust.

We can help you with:

Want an API your clients can rely on? Talk to our API experts today.

lakhya

Writes about Web & Architecture at Pheonix Solutions.

Leave a Comment

Scroll to Top