← Back to Backend, page 1

backend-0002 · Easy fresher

Which HTTP status codes should a REST API return for success, client errors and server errors, and how do you choose between similar ones such as 400 vs 422 and 401 vs 403?

Use the class of the code to say who is at fault: 2xx success, 3xx redirect or cached, 4xx the client must change the request, 5xx the server failed (retry may help). Pick the most specific code: 201 for created, 204 for no body, 400 for malformed input, 422 for valid syntax but failed validation, 401 when authentication is missing or wrong, 403 when the user is known but not allowed, 404 for missing, 409 for a state conflict, 429 for rate limits, 503 for temporary unavailability.

Full answer

Success

  • 200 OK with a body. 201 Created with a Location header. 202 Accepted when the work is queued. 204 No Content for success with no body (DELETE, some PUT).

Client errors (do not retry unchanged)

  • 400 Bad Request: the request cannot be parsed (broken JSON, wrong type).
  • 401 Unauthorized: no valid credentials. (The name is historic. It means "unauthenticated".) Send WWW-Authenticate.
  • 403 Forbidden: credentials are valid but the action is not allowed.
  • 404 Not Found: no such resource. Some APIs return 404 instead of 403 to hide that a resource exists.
  • 409 Conflict: the request clashes with the current state (duplicate email, version mismatch). 412 Precondition Failed for failed If-Match.
  • 422 Unprocessable Content: the syntax is fine but the values break business or validation rules.
  • 429 Too Many Requests, with Retry-After.

Server errors (the client may retry)

  • 500 unexpected failure, 502 or 504 bad or slow upstream, 503 temporarily unavailable (with Retry-After).

Also return a consistent error body (a machine code, a human message, field details, a request id). RFC 9457 (problem details) is a standard shape. Never put stack traces in responses.

javascript
const http = require('node:http');

// Each scenario returns the status that a well designed API would use.
const scenarios = {
  created:     (res) => res.writeHead(201, { location: '/students/7' }).end('{"id":7}'),
  deleted:     (res) => res.writeHead(204).end(),
  brokenJson:  (res) => res.writeHead(400).end('{"code":"invalid_json"}'),
  badEmail:    (res) => res.writeHead(422).end('{"code":"validation_failed","fields":{"email":"must be an email"}}'),
  noToken:     (res) => res.writeHead(401, { 'www-authenticate': 'Bearer' }).end('{"code":"unauthenticated"}'),
  wrongRole:   (res) => res.writeHead(403).end('{"code":"forbidden"}'),
  missing:     (res) => res.writeHead(404).end('{"code":"not_found"}'),
  duplicate:   (res) => res.writeHead(409).end('{"code":"email_taken"}'),
  tooMany:     (res) => res.writeHead(429, { 'retry-after': '30' }).end('{"code":"rate_limited"}'),
  maintenance: (res) => res.writeHead(503, { 'retry-after': '120' }).end('{"code":"unavailable"}'),
};
const retryable = (status) => status === 429 || status === 503 || status === 502 || status === 504;

const server = http.createServer((req, res) => (scenarios[req.url.slice(1)] || ((r) => r.writeHead(404).end()))(res));
server.listen(0, '127.0.0.1', async () => {
  for (const name of Object.keys(scenarios)) {
    const r = await fetch(`http://127.0.0.1:${server.address().port}/${name}`);
    const extra = ['location', 'www-authenticate', 'retry-after'].filter((h) => r.headers.has(h)).map((h) => `${h}: ${r.headers.get(h)}`).join(', ');
    console.log(name.padEnd(12), r.status, ('client may retry: ' + retryable(r.status)).padEnd(24), extra);
  }
  server.close();
});

The server answers each scenario with the status an API should use. The client prints the status, the headers that matter and whether a retry makes sense. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): created 201 client may retry: false location: /students/7 deleted 204 client may retry: false brokenJson 400 client may retry: false badEmail 422 client may retry: false noToken 401 client may retry: false www-authenticate: Bearer wrongRole 403 client may retry: false missing 404 client may retry: false duplicate 409 client may retry: false tooMany 429 client may retry: true retry-after: 30 maintenance 503 client may retry: true retry-after: 120

Key points

  • The first digit says whose fault it is.
  • 401 means unauthenticated; 403 means not allowed.
  • 400 is a bad request format; 422 is a failed validation.
  • 409 and 412 describe state conflicts; 429 describes rate limits.
  • Use one error body shape everywhere.

Common mistakes

  • Returning 200 with an error message in the body.
  • Using 500 for validation errors.
  • Mixing up 401 and 403.
  • Returning 404 for an empty list (use 200 and []).
  • Leaking stack traces in error bodies.

Follow-ups

  • When would you return 202 instead of 201?
  • What is a problem details (RFC 9457) response?
  • Why do some APIs return 404 for forbidden resources?

Tips

  • Group by who is at fault.
  • Contrast 401 with 403 in one sentence.
  • Name Retry-After.