AnyLearn
All lessons
Programmingbeginner

HTTP Status Codes: Understanding Each Class and When to Use Them

HTTP status codes are essential for effective communication between clients and servers on the web. This lesson breaks down each class of status codes (1xx, 2xx, 3xx, 4xx, 5xx), explains their meaning, and provides practical guidance on when to use them in your applications.

Not signed in — your progress and quiz score won't be saved.
Lesson progress1 / 10

The Language of the Web: Why Status Codes Matter

Every time your web browser or application requests a resource from a server, the server responds with an HTTP status code. This three-digit number, often unseen by the end-user, is a critical piece of information that tells the client the outcome of its request. Think of it as a brief, standardized message about the transaction's success or failure, and crucially, why.

Understanding these codes is fundamental for anyone working with web development, APIs, or even just troubleshooting network issues. A 200 OK means everything went smoothly, while a 404 Not Found indicates a missing resource. Knowing the difference, and the nuances within each class, allows developers to build robust applications that handle various scenarios gracefully, provide meaningful feedback to users, and debug problems efficiently. Without status codes, the client would have no standardized way to interpret a server's response, leading to unpredictable behavior and difficult-to-diagnose issues.

Full lesson text

All 10 steps on one page — for reading, reference, and search.

Show

1. The Language of the Web: Why Status Codes Matter

Every time your web browser or application requests a resource from a server, the server responds with an HTTP status code. This three-digit number, often unseen by the end-user, is a critical piece of information that tells the client the outcome of its request. Think of it as a brief, standardized message about the transaction's success or failure, and crucially, why.

Understanding these codes is fundamental for anyone working with web development, APIs, or even just troubleshooting network issues. A 200 OK means everything went smoothly, while a 404 Not Found indicates a missing resource. Knowing the difference, and the nuances within each class, allows developers to build robust applications that handle various scenarios gracefully, provide meaningful feedback to users, and debug problems efficiently. Without status codes, the client would have no standardized way to interpret a server's response, leading to unpredictable behavior and difficult-to-diagnose issues.

2. 1xx Informational Responses: Just a Heads-Up

The 1xx series of status codes are informational responses, meaning the server has received the request headers and the client should continue with its request or ignore the response if it's already finished. These codes are somewhat rare in typical browser interactions but are important for specific network protocols and proxy behaviors.

They essentially tell the client, "I've got your request, but I'm not done processing it yet. Hang tight or send the rest of your data." They are temporary responses, indicating that the request process has been initiated and the server is waiting for the client to proceed or acknowledge.

Common 1xx Codes:

  • 100 Continue: The client should continue with its request. This is typically sent in response to an Expect: 100-continue request header from the client, indicating that the client intends to send a large request body and wants to ensure the server is willing to accept it before sending the full payload.
  • 101 Switching Protocols: The server understands and is willing to comply with a client's request to switch to a different protocol, such as upgrading from HTTP/1.1 to WebSockets.

3. 2xx Success: Everything Went Right!

The 2xx class of status codes indicates that the client's request was successfully received, understood, and accepted. These are the codes you want to see most often, as they signify a successful transaction from the server's perspective. However, 'success' can have different nuances, which is why there are several codes in this class.

Key 2xx Codes:

  • 200 OK: The most common success code. It means the request has succeeded. The payload sent in a 200 response depends on the request method (e.g., GET includes the requested resource, POST might include a representation of the result).
  • 201 Created: The request has been fulfilled and resulted in a new resource being created. This is typically sent after a successful POST request that creates a new item on the server, and the response usually includes a Location header pointing to the newly created resource, along with a representation of that resource in the body.
  • 202 Accepted: The request has been accepted for processing, but the processing has not been completed. It's often used for asynchronous operations where the server will eventually process the request, but not immediately. There's no guarantee that the operation will eventually succeed.
  • 204 No Content: The server successfully processed the request, but is not returning any content. This is useful for PUT, DELETE, or POST requests where the client doesn't need to navigate away from its current page and only cares that the operation was successful without needing a new resource or updated state representation.

4. Successful Request Flow (2xx)

A simple flow demonstrating how a client and server interact for a successful operation.

flowchart TD
  Client["Client Request (e.g., GET /data)"] --> Server[Server]
  Server --> Process[Process Request]
  Process --> Found[Resource Found?]
  Found -- Yes --> Response["Server Response (200 OK + Data)"]
  Found -- No --> ClientError["Error (e.g., 404 Not Found)"]
  Response --> Client

5. 3xx Redirection: Go Somewhere Else

The 3xx class of status codes indicates that the client must take additional action to complete the request. These codes are primarily used for redirection, instructing the client (like a web browser) to fetch the requested resource from a different URI. Redirection is crucial for maintaining website structure, moving content, and handling temporary resource unavailability.

Important Considerations for 3xx Codes:

  • SEO Impact: Search engines treat permanent and temporary redirects differently for ranking purposes. 301 typically passes on link equity, while 302/307 do not.
  • Client Behavior: Some clients might change the request method (e.g., POST to GET) after receiving certain redirect codes, which can have unintended side effects if not accounted for.

Key 3xx Codes:

  • 301 Moved Permanently: The requested resource has been permanently moved to a new URI. Clients should update any links to the old URI with the new one. The new URI is provided in the Location header.
  • 302 Found (formerly 'Moved Temporarily'): The requested resource is temporarily located at a different URI. The client should continue to use the original URI for future requests. The new URI is in the Location header.
  • 303 See Other: The server is redirecting the client to another resource, typically following a POST request. This code indicates that the new resource should be retrieved using a GET method, preventing issues with re-submitting forms.
  • 304 Not Modified: This is a performance optimization. If the client has a cached version of a resource and sends conditional request headers (If-Modified-Since or If-None-Match), the server responds with 304 if the resource hasn't changed, telling the client to use its cached copy.

6. Choosing the Right Redirect: 301, 302, 307

Selecting the correct redirect status code is vital, especially for web applications and SEO. Misusing them can lead to broken links, incorrect caching, and poor search engine rankings. While 301 is for permanent moves, 302 and 307 are for temporary ones, but they differ in how they instruct the client to handle the request method.

CodePurposeMethod Change Allowed?Caching ImplicationsSEO Impact
301Permanent RedirectionYes (POST to GET)Strong caching encouragedPasses link equity
302Temporary RedirectionYes (POST to GET)No caching by defaultDoes NOT pass link equity
307Temporary RedirectionNo (Preserves method)No caching by defaultDoes NOT pass link equity

When to use each:

  • Use 301 Moved Permanently when a page or resource has truly moved to a new URL and won't be returning to the old one. This is common during site redesigns or URL structure changes.
  • Use 302 Found (or 303 See Other for POST requests to prevent resubmission) for temporary redirects where the resource might eventually return to its original location. This is good for A/B testing or maintenance pages.
  • Use 307 Temporary Redirect when you need to ensure the client repeats the request to the new URI with the same HTTP method used in the original request. This is particularly important for POST or PUT requests that should not be converted to GET.

7. 4xx Client Errors: It's Not You, It's Me (the Client)

The 4xx class of status codes indicates that there was an error with the client's request. The server understands the request but cannot or will not process it due to something the client did wrong. These are crucial for API developers to provide clear, actionable feedback to users and other applications.

Key 4xx Codes:

  • 400 Bad Request: The server cannot process the request due to malformed syntax, invalid request message framing, or deceptive request routing. This is a general error for when the request itself is structurally incorrect.
  • 401 Unauthorized: The client must authenticate itself to get the requested response. This usually means the client hasn't provided valid authentication credentials (e.g., an API key or token) or the credentials provided are insufficient. It's often accompanied by a WWW-Authenticate header.
  • 403 Forbidden: The client does not have access rights to the content, so the server is refusing to give the requested resource. Unlike 401, authentication might have been provided, but the authenticated user simply doesn't have permission to access that specific resource.
  • 404 Not Found: The most famous client error. The server cannot find the requested resource. This is often because the URL is incorrect or the resource has been moved or deleted without a redirect. It does not indicate whether the resource might be available again in the future.

8. More Client Errors and Best Practices

Beyond the common 400s and 404s, several other 4xx codes provide more specific information about client-side issues. Using the most precise code helps clients and developers understand exactly what went wrong.

Additional Key 4xx Codes:

  • 405 Method Not Allowed: The request method (e.g., POST, GET, PUT) is known by the server but has been disabled or is not allowed for the requested resource. For example, trying to POST to a read-only endpoint.
  • 409 Conflict: The request could not be completed due to a conflict with the current state of the target resource. This is often used in situations like concurrent updates, where a client tries to update a resource that has been modified by another client since it was last fetched (e.g., using If-Match header).
  • 429 Too Many Requests: The user has sent too many requests in a given amount of time ("rate limiting"). This code is often accompanied by Retry-After headers indicating how long the client should wait before making another request.

Example of handling a 404 in Python (requests library):

import requests

response = requests.get('https://api.example.com/nonexistent-resource')

if response.status_code == 404:
    print('Error: Resource not found. Please check the URL.')
elif response.status_code == 401:
    print('Error: Unauthorized. Please provide valid credentials.')
else:
    response.raise_for_status() # Raises an exception for 4xx/5xx codes
    print('Request successful!')

Heads up: Always aim to return the most specific 4xx error code possible. A generic 400 Bad Request is less helpful than 401 Unauthorized or 404 Not Found.

9. 5xx Server Errors: It's Not Me, It's You (the Server)

The 5xx class of status codes indicates that the server failed to fulfill an apparently valid request. These errors mean there's a problem on the server's side, preventing it from handling the request properly. As a developer, seeing these codes usually points to issues within your backend application, database, or server infrastructure.

Key 5xx Codes:

  • 500 Internal Server Error: A generic error message, given when an unexpected condition was encountered and no more specific message is suitable. This is often a fallback for unhandled exceptions in server-side code. If you see this in production, it's time to check your server logs!
  • 501 Not Implemented: The server does not support the functionality required to fulfill the request. This can mean the server doesn't recognize the request method or lacks the ability to handle it (e.g., attempting a PATCH request on a server that only supports GET and POST).
  • 502 Bad Gateway: The server, while acting as a gateway or proxy, received an invalid response from an upstream server it accessed in attempting to fulfill the request. This often indicates a problem between your web server (e.g., Nginx, Apache) and your application server (e.g., Gunicorn, Node.js app).
  • 503 Service Unavailable: The server is currently unable to handle the request due to temporary overloading or maintenance of the server. This is often accompanied by a Retry-After header, suggesting how long the client should wait before trying again.
  • 504 Gateway Timeout: The server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access to complete the request. Similar to 502, but specifically indicates a timeout issue.

10. Common Misuses and Best Practices for Status Codes

Even experienced developers can sometimes misuse HTTP status codes. Understanding common pitfalls and adhering to best practices ensures your APIs are robust and easy to interact with.

Common Misuses:

  • Returning 200 OK for errors: Embedding error messages within a 200 OK response body makes it harder for automated clients to detect failures. Always use an appropriate 4xx or 5xx code for errors.
  • Confusing 401 Unauthorized and 403 Forbidden: 401 means 'authenticate first' (you are not logged in or your token is invalid). 403 means 'you are logged in, but you don't have permission for this specific action/resource.' (you are logged in as a regular user, but trying to access an admin-only endpoint).
  • Sending a body with 204 No Content: By definition, a 204 response must not contain a message body. Clients expect this for performance and consistency.

Best Practices:

  • Be Specific: Use the most precise status code available. 422 Unprocessable Entity is better than a generic 400 Bad Request if the request body's semantics are wrong.
  • Consistent Error Bodies: When returning 4xx or 5xx codes, provide a consistent, machine-readable error body (e.g., JSON) with details like an error_code, message, and potentially details or links for more information.
  • Idempotency with Methods: Understand how HTTP methods and status codes relate to idempotency. A PUT request should be idempotent (applying it multiple times has the same effect as applying it once), and its success should often return 200 OK or 204 No Content.
  • Use Retry-After: For 429 Too Many Requests or 503 Service Unavailable, always include a Retry-After header to guide clients on when to try again, preventing exponential backoff issues.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. Which HTTP status code class indicates a client-side error?
    • 1xx
    • 2xx
    • 3xx
    • 4xx
  2. A `POST` request successfully created a new resource on the server. Which status code should the server most appropriately return?
    • 200 OK
    • 201 Created
    • 202 Accepted
    • 204 No Content
  3. What is the primary difference between a `301 Moved Permanently` and a `302 Found` redirect?
    • 301 is for client errors, 302 is for server errors.
    • 301 suggests the client use the new URL for future requests, 302 suggests using the original URL.
    • 301 allows the client to change the request method, 302 does not.
    • 301 is cached by default, 302 is never cached.
  4. You try to access an API endpoint that requires authentication, but you forgot to include your API key. Which HTTP status code would you most likely receive?
    • 400 Bad Request
    • 403 Forbidden
    • 401 Unauthorized
    • 404 Not Found
  5. Which of the following status codes should be used when the server is temporarily overloaded or undergoing maintenance?
    • 500 Internal Server Error
    • 501 Not Implemented
    • 503 Service Unavailable
    • 504 Gateway Timeout

Related lessons