SoftwareSideHustles
Concepts

HTTP Status Codes for REST APIs: Which One to Return (401 vs 403, 400 vs 422 and More)

A practical guide to choosing HTTP status codes in a REST API — the codes you actually need, the confusing pairs (401/403, 400/422, 200/204, 404/410, 502/503/504), and a consistent error response format.

By Software Side Hustles Editorial Team · Published · Updated · 5 min read

Quick answer: use 2xx for success (200 with a body, 201 when you created something, 204 with no body), 4xx when the client must change the request (400 malformed, 401 not authenticated, 403 not allowed, 404 not found, 409 conflict, 422 failed validation, 429 rate-limited) and 5xx when the server failed (500 bug, 502/504 upstream problems, 503 temporarily unavailable). The most-confused pair: 401 means "who are you?", 403 means "I know who you are, and no".

The status codes you actually need

CodeNameUse it when
200OKSuccessful GET, or an update that returns the resource
201CreatedA POST created a resource; include a Location header
202AcceptedWork was queued and will finish later
204No ContentSuccess with no body, e.g. DELETE
301 / 308Moved Permanently / Permanent RedirectA URL changed for good (308 keeps the method)
302 / 307Found / Temporary RedirectTemporary redirect (307 keeps the method)
304Not ModifiedConditional GET: the client's cached copy is still valid
400Bad RequestMalformed syntax: invalid JSON, wrong types, missing required parameter
401UnauthorizedNo credentials, or invalid/expired credentials
403ForbiddenAuthenticated, but not permitted
404Not FoundThe resource does not exist (or you will not reveal it does)
405Method Not Allowede.g. DELETE on an endpoint that only supports GET
409ConflictThe request conflicts with current state: duplicate email, version mismatch
410GoneThe resource existed but has been permanently removed
415Unsupported Media TypeWrong Content-Type, e.g. form data sent to a JSON endpoint
422Unprocessable ContentWell-formed but semantically invalid: end date before start date
429Too Many RequestsRate limit exceeded; include Retry-After
500Internal Server ErrorAn unexpected bug or unhandled exception
502Bad GatewayA proxy got an invalid response from the upstream server
503Service UnavailableOverloaded or in maintenance; temporary
504Gateway TimeoutA proxy timed out waiting for the upstream server

401 vs 403

  • 401 Unauthorized is really "unauthenticated": the request has no valid credentials. The client should log in or refresh its token and try again. The response should include a WWW-Authenticate header describing the scheme.
  • 403 Forbidden means the server knows who the caller is, and they lack permission. Logging in again will not help.

An expired token is 401. A regular user calling an admin endpoint is 403.

400 vs 422

  • 400 Bad Request — the server cannot even parse or interpret the request: invalid JSON, a string where a number belongs, a missing required field.
  • 422 Unprocessable Content — the request is well-formed, but violates business rules: a negative quantity, an end date before the start date, a password that fails the policy.

Many APIs use 400 for both, which is acceptable if you are consistent and your error body explains which field failed. What matters most is that clients can tell "fix your request" (4xx) from "try again later" (5xx).

404 vs 403 vs 410

Returning 403 for another user's private resource confirms that it exists. When existence itself is sensitive (other users' orders, private repositories), return 404 for both "does not exist" and "exists but not yours". Use 410 Gone only when you want clients and search engines to know a resource was intentionally removed.

200 vs 201 vs 204

  • POST /orders that creates an order: 201, with the new resource (or its ID) in the body and Location: /orders/123.
  • PUT or PATCH that returns the updated resource: 200. If nothing is returned: 204.
  • DELETE: 204 is conventional. A repeated DELETE of something already deleted can return 404 or 204; either is defensible if documented.

Do not return 200 with {"success": false} for errors. Clients, proxies, monitoring and retry logic all rely on the status code; burying failures in the body breaks every one of them.

409 Conflict and concurrency

Use 409 for duplicates (a username already taken) and for optimistic-locking conflicts: the client sent If-Match: "v3" but the resource is now at version 4. With conditional requests specifically, 412 Precondition Failed is the precise code.

5xx: whose fault was it?

  • 500 — your code threw an unexpected exception. Log it with a stack trace, return a generic message (never the stack trace itself), and fix the bug.
  • 502 — a gateway or load balancer received a bad response from your app: it crashed mid-request, closed the connection, or is not listening on the expected port.
  • 503 — the service is temporarily unable to handle requests: overload, maintenance, a dependency circuit breaker. Add Retry-After.
  • 504 — a gateway gave up waiting for your app; the request took longer than the proxy's timeout.

Clients may safely retry 502, 503 and 504 (with backoff) for idempotent requests, and should not blindly retry 500 or any 4xx.

A consistent error format

RFC 9457 ("Problem Details for HTTP APIs") defines a standard JSON shape, served as application/problem+json:

json
{
"type": "https://example.com/problems/validation-error",
"title": "Your request is invalid",
"status": 422,
"detail": "end_date must be after start_date",
"errors": [{ "field": "end_date", "message": "must be after start_date" }]
}

Spring Boot (ProblemDetail), ASP.NET Core (ProblemDetails) and many other frameworks support it out of the box. Whatever format you choose, use the same one for every endpoint, include a machine-readable code, and add a request ID that matches your logs.

Idempotency and methods

GET, PUT and DELETE should be idempotent: repeating them has the same effect as doing them once. POST is not, which is why retries can create duplicate orders. For payment-like POST endpoints, accept an Idempotency-Key header and return the original result for repeated keys.

Frequently asked questions

Should validation errors be 400 or 422?

Either works if you are consistent. 422 distinguishes "valid JSON, invalid values" from "unparseable request", which some clients find useful.

What status code for a failed login?

401 for wrong credentials. Use the same response for "unknown user" and "wrong password" so attackers cannot discover which accounts exist.

Is 418 a real status code?

"I'm a teapot" began as an April Fools' joke (RFC 2324). It is reserved so nobody assigns it, but do not use it in a real API.

Where this skill pays off

API design questions — "what should this endpoint return?" — are common in AI coding evaluations, and a response that returns 200 with an error body or leaks a stack trace in a 500 should lose. Judging those trade-offs is paid work; see what makes one coding solution better than another.

Cookies on this site

We use essential cookies to run the questionnaire, practice labs and sign-in. With your permission we'd also like to use analytics to understand which pages help people, and advertising cookies to measure our Google Ads. Rejecting never limits any feature. Cookie policy