Web & Mobile Development

HTTP Status Codes: A Complete Reference With Meaning and Correct Use

Beginner15 min readUpdated

A status code is the first thing a client learns about a response and often the only thing an intermediary reads, so choosing the wrong one quietly breaks caches, retries and error handling. This reference explains the model behind the five classes, tables every registered code with its meaning and appropriate use, then works through the confusable pairs, redirect and caching rules, and how to pick codes when designing an API.

What you will learn

  • Explain the structure of a status line and what each of the five classes signals
  • Look up any status code and know when it is the correct response
  • Choose correctly between the pairs that are routinely confused, such as 301 and 308 or 401 and 403
  • Apply redirect semantics without changing a request method by accident
  • Predict which responses are cacheable and how conditional requests produce 304
  • Pick appropriate status codes when designing an HTTP API and report errors consistently

Every HTTP response opens with a three-digit number, and that number is the only part of the response many systems ever read. A browser decides whether to follow a redirect from it. A cache decides whether it may store the body. A load balancer decides whether the backend is healthy. A client library decides whether to raise an exception or retry. Choosing the wrong code does not usually produce a visible error — it produces a subtle one, months later, when a proxy caches something it should not have or a retry loop hammers an endpoint that was never going to succeed.

The definitive specification is RFC 9110, which replaced the older RFC 7231 family and is now the single document describing HTTP semantics across versions 1.1, 2 and 3. The authoritative list of assigned codes is the IANA HTTP Status Code Registry. This page is a practical companion to both: what each code means, when it is the right answer, and where developers reliably get it wrong.

The status line and the five classes

In HTTP/1.1 a response begins with the protocol version, the status code and a reason phrase:

HTTP/1.1 404 Not Found
Content-Type: application/problem+json
Content-Length: 91

{"type":"https://example.com/errors/no-such-order","title":"Order not found","status":404}

The reason phrase is advisory. It exists for humans reading a raw stream, clients must not act on it, and HTTP/2 and HTTP/3 removed it entirely — they carry the numeric code as a pseudo-header and nothing else. Never parse it.

The first digit is the part with defined meaning, and it is a contract: a client that receives an unrecognised code must treat it as the generic x00 of its class. A response of 499 is handled as 400, a 572 as 500. That rule is what allows new codes to be registered without breaking existing clients, and it is why picking a plausible-sounding unregistered number is less harmful than picking a registered one with the wrong meaning — but still worse than picking correctly.

ClassNameMeaning
1xxInformationalThe request was received; processing continues. An interim response.
2xxSuccessfulThe request was received, understood and accepted.
3xxRedirectionFurther action is needed to complete the request.
4xxClient errorThe request is faulty and will fail again unless changed.
5xxServer errorThe request may be valid; the server failed to fulfil it.

The 4xx/5xx boundary carries operational weight. It is what separates "your fault" from "our fault" on a dashboard, what health checks watch, and what error budgets are calculated from. Returning 500 for a malformed request pollutes your own alerting; returning 400 for an internal failure hides a real outage.

1xx — Informational

Interim responses, sent before the final one. A client that does not understand a 1xx must ignore it and keep waiting.

CodeNameWhen it appears
100ContinueThe client sent Expect: 100-continue with headers only, asking whether to send a large body. The server replies 100 to invite it, or a 4xx to reject before the upload starts.
101Switching ProtocolsThe server agrees to change protocol, as in a WebSocket handshake following Upgrade: websocket.
102ProcessingA WebDAV holding response for long operations. Deprecated; use 103 or keep the connection open.
103Early HintsSent before the final response to carry Link headers so the browser can preload or preconnect while the server is still working.

Early Hints is the only one of the four worth adding deliberately to a modern application: on a slow server-rendered page it lets the browser start fetching stylesheets and fonts before the HTML exists.

2xx — Successful

CodeNameWhen to use it
200OKThe default success. The body carries the result of the request.
201CreatedA new resource was created. Include a Location header pointing at it, and usually the representation in the body.
202AcceptedThe request was accepted for asynchronous processing and the outcome is not yet known. Return a way to check progress.
203Non-Authoritative InformationA transforming proxy modified the payload. Rare outside intermediaries.
204No ContentSuccess with nothing to return — a DELETE, or a PUT where the client already has the state. There must be no body.
205Reset ContentSuccess; the client should clear the form that produced the request. Rarely used.
206Partial ContentA successful Range request. Underpins resumable downloads and media seeking.
207Multi-StatusWebDAV: an XML body containing several independent status codes.
208Already ReportedWebDAV: members of a collection were already enumerated.
226IM UsedThe response is the result of applying instance manipulations, such as a delta encoding.

The pair that matters day to day is 201 versus 200. If the request created something addressable, say so and give its address — clients and caches can then work with the new resource without guessing its URL. And 204 means exactly no body: sending JSON with it is a specification violation that some clients handle by throwing.

3xx — Redirection

CodeNameMethod preserved?When to use it
300Multiple Choicesn/aSeveral representations exist and the client should choose. Almost never used.
301Moved PermanentlyNo, in practiceThe resource has a new permanent URL. Historically rewrites POST to GET.
302FoundNo, in practiceTemporary relocation. Also rewrites POST to GET in every real client.
303See OtherNo, by design"Fetch the result from this other URL with GET." The correct answer to a completed form submission.
304Not Modifiedn/aThe cached copy is still fresh; there is no body. Answer to a conditional request.
305Use Proxyn/aDeprecated for security reasons. Do not use.
306(unused)n/aReserved; was "Switch Proxy".
307Temporary RedirectYesTemporary relocation with the method and body preserved.
308Permanent RedirectYesPermanent relocation with the method and body preserved.

Getting redirects right

The historical mess is worth understanding because it still shapes behaviour. RFC 2616 said that 301 and 302 must not change the request method without user confirmation. Browsers ignored that and turned a redirected POST into a GET, so the specification eventually conceded the point and documented the real behaviour. That left no way to say "moved, and keep the method", which is why 307 and 308 were added.

The practical rules:

  • 301 versus 308. Both are permanent, and both are cached by clients — often indefinitely — so neither should be used casually. Choose 301 for ordinary site moves, canonical host and scheme redirects and changed page addresses, because it is universally supported and search engines have decades of behaviour built around it. Choose 308 when the endpoint accepts POST, PUT or PATCH and the method must survive, such as a versioned API path change.
  • 302 versus 307. Both are temporary. 302 will convert a POST to a GET; 307 will not. If you are redirecting a form submission and want the browser to re-POST to the new location, you need 307. If you want the safe behaviour, 303 states it explicitly rather than relying on a de facto rule.
  • 303 after a write. The Post/Redirect/Get pattern exists to stop a browser refresh from resubmitting a payment. Respond to the successful POST with 303 and a Location pointing at the confirmation page.

Two operational cautions. Permanent redirects are hard to take back: a browser that cached a 301 may not ask again for a very long time, so test with a temporary code first and promote it once you are sure. And every redirect costs a round trip — chains of three or four, common after several site migrations, are a measurable performance problem and should be collapsed to a single hop. When you are debugging a redirect that mangles query parameters, the URL encoder/decoder makes the difference visible immediately.

4xx — Client error

CodeNameWhen to use it
400Bad RequestThe request is malformed — invalid syntax, unparseable body, bad framing. Not a general-purpose error.
401UnauthorizedAuthentication is missing or invalid. Must include WWW-Authenticate.
402Payment RequiredReserved; used by some APIs for quota or billing failures.
403ForbiddenThe server understood the identity and refuses. Re-authenticating will not help.
404Not FoundNo resource at this URL, or the server declines to say whether one exists.
405Method Not AllowedThe URL exists but not for this method. Must include an Allow header.
406Not AcceptableNo representation matches the Accept headers.
407Proxy Authentication RequiredLike 401, but for a proxy; uses Proxy-Authenticate.
408Request TimeoutThe client took too long to send the request. Safe to retry.
409ConflictThe request conflicts with the current state — a duplicate key, a concurrent edit, an invalid state transition.
410GoneDeliberately removed and not coming back. Stronger and more useful than 404 when you know.
411Length RequiredThe request needs a Content-Length.
412Precondition FailedAn If-Match or If-Unmodified-Since precondition did not hold. The basis of optimistic locking.
413Content Too LargeThe body exceeds the server's limit. Formerly "Payload Too Large".
414URI Too LongThe request target exceeds the server's limit.
415Unsupported Media TypeThe Content-Type is not one the endpoint accepts.
416Range Not SatisfiableThe requested byte range lies outside the resource.
417Expectation FailedThe Expect header cannot be satisfied.
418I'm a teapotAn April Fools' joke from 1998, reserved by IANA so it will never be assigned.
421Misdirected RequestThe connection reached a server unable to produce a response for this authority. Seen with HTTP/2 connection coalescing.
422Unprocessable ContentSyntactically valid, semantically wrong. The usual choice for business-rule validation failures.
423LockedWebDAV: the resource is locked.
424Failed DependencyWebDAV: a dependent request failed.
425Too EarlyThe server will not process a replayed early-data request.
426Upgrade RequiredThe client must switch protocol, for example to TLS.
428Precondition RequiredThe server requires a conditional request, to prevent lost updates.
429Too Many RequestsRate limited. Include Retry-After.
431Request Header Fields Too LargeHeaders exceed the limit — usually an oversized cookie.
451Unavailable For Legal ReasonsBlocked by a legal demand. The number is a nod to Fahrenheit 451.

5xx — Server error

CodeNameWhen to use it
500Internal Server ErrorAn unhandled failure. The catch-all — never the deliberate answer to a known condition.
501Not ImplementedThe server does not support the method at all.
502Bad GatewayA gateway received an invalid response from an upstream server.
503Service UnavailableTemporarily unable to handle the request — overload or maintenance. Include Retry-After.
504Gateway TimeoutA gateway did not receive a timely response from an upstream server.
505HTTP Version Not SupportedThe protocol version in the request is unsupported.
506Variant Also NegotiatesA content-negotiation misconfiguration.
507Insufficient StorageWebDAV: not enough space to complete the request.
508Loop DetectedWebDAV: an infinite loop while processing.
510Not ExtendedObsoleted; the extension framework it belonged to was never adopted.
511Network Authentication RequiredA captive portal demanding sign-in. Must be generated by the intercepting proxy, never by an origin server.

The pairs that are routinely confused

401 versus 403. 401 says "I do not know who you are, or your credentials were rejected" and obliges the server to send WWW-Authenticate. 403 says "I know who you are and the answer is still no." The practical consequence is client behaviour: a 401 should trigger a login prompt or a token refresh, a 403 should not. Many APIs return 403 for expired tokens, which sends clients into a permanent failure state instead of a refresh.

There is a third option worth knowing. When even the existence of a resource is confidential, returning 404 to an unauthorised caller is a legitimate hardening measure — it avoids confirming that an object with that identifier exists.

400 versus 422. 400 is about form, 422 is about meaning. A body that is not valid JSON is a 400; a valid JSON body whose endDate precedes its startDate is a 422. Some well-known APIs use 400 for everything and stay perfectly usable, so the far more important property is consistency plus a body that names the offending fields. RFC 9457 defines a standard problem-details media type for exactly this, which is worth adopting so clients can parse errors uniformly.

404 versus 410. 404 means "nothing here, and I am not saying whether there ever was". 410 means "this existed and has been deliberately removed". If you know the resource is gone for good, 410 is more informative: crawlers drop the URL faster and clients can stop retrying.

409 versus 422 versus 412. 409 is a conflict with the current state of the resource — creating a user whose email already exists, or transitioning an order that has already shipped. 422 is a problem with the submitted content alone. 412 is the answer to a failed precondition on a conditional request, which is how optimistic concurrency control is implemented with ETag and If-Match.

502 versus 503 versus 504. All three usually come from a proxy rather than your application, and telling them apart is the fastest way to locate an incident. 502 means the upstream answered with something unintelligible — often a crashed process or a protocol mismatch. 503 means the server is up and deliberately refusing right now: overloaded, in maintenance, or with no healthy backend in the pool. 504 means the upstream never answered in time, which points at a slow dependency, a deadlock or a timeout set lower in the proxy than in the application. When a gateway sits in front of your services, its own timeout and retry configuration shapes which of the three your users see — see API management and gateways.

200 with an error inside. The most damaging anti-pattern in the list. Every intermediary, every monitoring system and every generic client treats it as success, so failures vanish from dashboards and retry logic never fires. Put the outcome in the status code and the detail in the body.

Caching and conditional requests

RFC 9111 defines which responses may be stored, and the status code is the starting point. Cacheable by default — meaning a shared cache may store them even with no explicit Cache-Control — are 200, 203, 204, 206, 300, 301, 308, 404, 405, 410, 414 and 501. Everything else requires explicit permission through cache directives. That list contains two surprises worth internalising: 404 and 301 are cacheable by default, so a temporarily broken deployment that returns 404, or a redirect published by mistake, can be remembered by caches and browsers long after you fix the origin.

In practice you should not rely on defaults. Cache-Control on the response settles it: no-store forbids storage entirely, no-cache allows storage but requires revalidation before reuse, private restricts it to the browser, max-age sets freshness in seconds, and must-revalidate forbids serving a stale copy after expiry.

Conditional requests are where 304 comes from. The server sends a validator — an ETag, or Last-Modified — and the client returns it on the next request:

GET /api/orders/42 HTTP/1.1
Host: example.com
If-None-Match: "a3f1c0"

HTTP/1.1 304 Not Modified
ETag: "a3f1c0"
Cache-Control: max-age=60

A 304 has no body, which is the whole point: the client already holds the content and only needed to know it is still valid. The same validators drive If-Match for writes, turning a lost-update race into a clean 412.

Choosing codes when you design an API

A small, deliberately chosen set beats exhaustive coverage. Most well-designed APIs use roughly a dozen codes: 200, 201, 202, 204, 301 or 308 for moved endpoints, 400, 401, 403, 404, 409, 422, 429, and 500 with 503 for degradation. Write them down as part of the API contract so every endpoint behaves the same way and clients can handle errors generically.

Beyond the choice itself, a few habits pay off. Return a machine-readable error body in a single, documented shape — RFC 9457 problem details, with a type, title, status, detail and any field-level errors — so a client can render a message without special-casing each endpoint. Do not leak stack traces or internal identifiers in that body; log them with a correlation id and return the id instead. Send Retry-After with 429 and 503 so clients back off intelligently rather than guessing, and make sure your own client code honours it. Include Allow with 405 and WWW-Authenticate with 401, both of which the specification requires. Prefer idempotent operations wherever possible, because idempotency is what makes retrying a 500 or a 504 safe. And keep in mind that fetch in the browser resolves for every status, so client code must check the status explicitly — a point covered in JavaScript fundamentals, while Angular's HttpClient takes the opposite convention and raises an error instead.

Finally, treat status codes as an operational instrument, not only a client contract. Graph 4xx and 5xx rates separately, alert on 5xx, and watch for the specific codes that mean something structural: a rise in 401 after a deployment usually means a token or clock problem, a rise in 504 means a dependency slowed down, and a rise in 429 means either an abusive client or a limit set too tight. The wider design considerations behind these choices are covered in REST API design, and the framework side in building REST APIs with Spring Boot.

Key takeaways

  • The first digit is the contract: unknown codes are handled as the generic x00 of their class, and the 4xx/5xx split decides whose fault an incident is on your dashboards.
  • Use 307 and 308 when a redirect must preserve the method and body; 301 and 302 rewrite POST to GET in practice, and 303 says so explicitly after a write.
  • 401 means "authenticate", 403 means "no"; 400 means malformed, 422 means semantically invalid; 502, 503 and 504 distinguish a broken upstream, a refusing server and a slow one.
  • 200 with an error in the body defeats caches, retries and monitoring — put the outcome in the status line and the detail in an RFC 9457 problem-details body.
  • 200, 301, 404 and several others are cacheable by default, so a mistaken redirect or a transient 404 can outlive the deployment that caused it unless Cache-Control says otherwise.
  • Pick a dozen codes, document them in the API contract, always send Retry-After, Allow and WWW-Authenticate where required, and check the code explicitly in client code.

Sources and further reading

Frequently asked questions

What is the difference between 401 and 403?
401 Unauthorized means the request lacked valid authentication, or the credentials supplied were not accepted; the response must include a WWW-Authenticate header telling the client how to authenticate, and retrying with better credentials may succeed. 403 Forbidden means the server understood who you are and is refusing anyway. Repeating a 403 with the same identity will never work, so a client should not prompt for a new login.
Should a validation failure be 400 or 422?
Use 400 Bad Request when the request itself is malformed — broken JSON, a missing required header, an unparseable parameter. Use 422 Unprocessable Content when the syntax is fine but the content is semantically wrong, such as an end date before a start date or a currency the account cannot use. Both are legitimate; what matters most is that your API is consistent and returns a machine-readable body explaining which field failed.
Is it acceptable to return 200 with an error in the body?
It is technically legal and almost always a mistake. Caches, proxies, retry policies, browser devtools, monitoring dashboards and client libraries all key off the status code, so a failure disguised as 200 becomes invisible to every layer except the code that parses your specific envelope. Use the status code as the outcome and the body for the detail, ideally in the RFC 9457 problem-details format.
Which status codes should a client retry?
Retry 408, 429, 502, 503 and 504, because they indicate a transient condition, and honour any Retry-After header before backing off exponentially with jitter. Do not retry 4xx codes other than those two: they describe a problem with the request that will still be there next time. Retrying 500 is only safe when the operation is idempotent, since the server may have partially applied it.