Designing REST APIs · Lesson 6 of 30
HTTP Status Codes for REST APIs
The status code is the first thing a client checks – before it even parses the body. Getting it right lets client libraries, monitoring tools and retry logic do the right thing automatically. A common anti-pattern is returning 200 OK with {"success": false} in the body; this lesson shows what to return instead.
In this lesson
- The five classes of status codes
- The codes a REST API actually uses
- 401 vs 403, 400 vs 422, 404 vs 410
- A real API returning each one
Five classes
The first digit tells the story
- 1xx Informationalrarely seen in APIs (100 Continue)
- 2xx Successthe request worked
- 3xx Redirectionlook elsewhere, or use your cached copy
- 4xx Client errorthe request was wrong – fix it before retrying
- 5xx Server errorthe server failed – retrying later may work
The codes you'll use
| Code | Use it when |
|---|---|
200 OK | successful GET, PUT or PATCH with a body |
201 Created | POST created a resource – include a Location header |
202 Accepted | the work was queued and will finish later (async jobs) |
204 No Content | success with nothing to return (DELETE, some PUTs) |
304 Not Modified | the client's cached copy is still valid (ETags) |
400 Bad Request | malformed request: invalid JSON, wrong types, missing parameters |
401 Unauthorized | not authenticated: missing or invalid credentials |
403 Forbidden | authenticated, but not allowed to do this |
404 Not Found | the resource doesn't exist (or you hide that it does) |
409 Conflict | conflicts with current state: duplicate email, already cancelled |
412 Precondition Failed | an If-Match check failed – someone else changed it |
415 Unsupported Media Type | the body isn't in a format you accept |
422 Unprocessable Content | well-formed but fails validation (business rules); older software, including Node.js, still prints the old name "Unprocessable Entity" |
429 Too Many Requests | rate limit exceeded – include Retry-After |
500 Internal Server Error | an unexpected bug – never a "normal" outcome |
502 / 503 / 504 | a dependency or the service is down or too slow |
A real API, code by code
// server.js
import express from 'express';
const app = express();
app.use(express.json());
const accounts = [{ id: 1, email: 'asha@example.com', owner: 'asha' }];
const tokens = { 'token-asha': 'asha', 'token-ravi': 'ravi' };
function auth(req, res, next) {
const token = req.get('Authorization')?.replace('Bearer ', '');
req.user = tokens[token];
if (!req.user) return res.status(401).set('WWW-Authenticate', 'Bearer').json({ error: 'Log in first' });
next();
}
app.post('/api/accounts', auth, (req, res) => {
const { email } = req.body ?? {};
if (typeof email !== 'string') return res.status(400).json({ error: 'email is required and must be a string' });
if (!email.includes('@')) return res.status(422).json({ error: 'email is not a valid address' });
if (accounts.some((a) => a.email === email)) return res.status(409).json({ error: 'An account with this email already exists' });
const account = { id: accounts.length + 1, email, owner: req.user };
accounts.push(account);
res.status(201).location(`/api/accounts/${account.id}`).json(account);
});
app.delete('/api/accounts/:id', auth, (req, res) => {
const account = accounts.find((a) => a.id === Number(req.params.id));
if (!account) return res.status(404).json({ error: 'Account not found' });
if (account.owner !== req.user) return res.status(403).json({ error: 'You can only delete your own account' });
accounts.splice(accounts.indexOf(account), 1);
res.status(204).end();
});
app.listen(process.env.PORT ?? 3000);
$ curl -X POST http://localhost:3000/api/accounts -H 'Content-Type: application/json' -d '{"email":"new@example.com"}'
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer
Content-Type: application/json; charset=utf-8
{
"error": "Log in first"
}
$ curl -X POST http://localhost:3000/api/accounts -H 'Authorization: Bearer token-ravi' -H 'Content-Type: application/json' -d '{"email":42}'
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
{
"error": "email is required and must be a string"
}
$ curl -X POST http://localhost:3000/api/accounts -H 'Authorization: Bearer token-ravi' -H 'Content-Type: application/json' -d '{"email":"ravi-at-example"}'
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json; charset=utf-8
{
"error": "email is not a valid address"
}
$ curl -X POST http://localhost:3000/api/accounts -H 'Authorization: Bearer token-ravi' -H 'Content-Type: application/json' -d '{"email":"asha@example.com"}'
HTTP/1.1 409 Conflict
Content-Type: application/json; charset=utf-8
{
"error": "An account with this email already exists"
}
$ curl -X POST http://localhost:3000/api/accounts -H 'Authorization: Bearer token-ravi' -H 'Content-Type: application/json' -d '{"email":"ravi@example.com"}'
HTTP/1.1 201 Created
Location: /api/accounts/2
Content-Type: application/json; charset=utf-8
{
"id": 2,
"email": "ravi@example.com",
"owner": "ravi"
}
$ curl -X DELETE http://localhost:3000/api/accounts/1 -H 'Authorization: Bearer token-ravi'
HTTP/1.1 403 Forbidden
Content-Type: application/json; charset=utf-8
{
"error": "You can only delete your own account"
}
$ curl -X DELETE http://localhost:3000/api/accounts/9 -H 'Authorization: Bearer token-ravi'
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
{
"error": "Account not found"
}Common confusions
- 401 vs 403 – 401 means "I don't know who you are" (send credentials); 403 means "I know who you are, and you can't do this". The name "Unauthorized" for 401 is a historical mistake – it really means unauthenticated.
- 400 vs 422 – 400 for requests the server can't even interpret (broken JSON, wrong types); 422 for valid JSON that breaks business rules. Many APIs use 400 for both, which is acceptable if consistent.
- 404 vs 403 – for private resources, returning 404 instead of 403 avoids revealing that something exists (GitHub does this for private repositories).
- 404 vs 410 – 410 Gone says it existed and was removed permanently.
- 500 means a bug or an unhandled failure. Expected situations – not found, invalid, conflict – are always 4xx.
Don't hide errors in a 200
200 OK {"success": false, "error": "Not found"} breaks every HTTP-aware tool: caches store it, monitoring counts it as success, and client code must parse every body to detect failure. Use the status code, and put details in the body.
Practice
Try it yourself
Pick the code: (a) cancelling an order that's already shipped, (b) a password reset link that expired, (c) uploading XML to a JSON-only endpoint, (d) creating a user (with the new user in the response).
Show solution
(a) 409 Conflict – the current state forbids it. (b) 410 Gone, or 422 / 400 with a clear message. (c) 415 Unsupported Media Type. (d) 201 Created with a Location header.
Quick check
Which code for a successful DELETE with no body?
204 No Content.
Missing token or not your record – which is 401 and which is 403?
Missing/invalid token: 401. Valid user without permission: 403.
Should a validation error ever be 500?
No – 500 is for unexpected server failures; validation errors are 400/422.
Summary
- 2xx success, 3xx redirect/cache, 4xx client mistakes, 5xx server failures.
- 201 + Location for creates, 204 for empty success, 409 for state conflicts, 429 with Retry-After.
- Never wrap errors in 200; reserve 500 for real bugs.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.