HTTP Status Codes


HTTP Status Codes




HTTP status codes are essential in web communication, acting as responses from a server to a client's request. These codes indicate whether a request has been successfully processed, if there are errors, or if further action is needed. This guide will explore the different types of HTTP status codes, their meanings, and how they are used in web development as well as Rest APIs. Eventually, you will increase your understanding and should be able to diagnose HTTP and API issues.

Context and Usage

HTTP status codes are an integral part of the HTTP response header. When a client, such as a web browser or a REST API client makes a request to a server, it receives a response. This response includes a status line, which contains the HTTP version, a status code, and a reason phrase. For instance, a response might start with HTTP/1.1 200 OK, indicating a successful processing of the request. Here the last two parts represent the status code.

Raw HTTP Response Envelope

HTTP/1.1 200 OK
Date: Sun, 03 Dec 2023 12:00:00 GMT
Server: Apache/2.4.1 (Unix)
Content-Type: text/html; charset=UTF-8
Content-Length: 1234

<!DOCTYPE html>
<html>
<head>
<title>Sample Web Page</title>
</head>
<body>
<h1>Welcome to the Sample Web Page</h1>
<p>This is a sample web page to demonstrate an HTTP response.</p>
</body>
</html>

Here are some popular examples of status codes with their uses.

  • 200 OK: This status code is used for successful GET, POST, PUT, or DELETE requests. For example, when a user requests a webpage (GET request), and the server successfully processes and returns the page, the response will typically have a 200 OK status code.

  • 201 Created: This indicates that a new resource has been successfully created, commonly used in response to POST requests. For instance, when a user submits a form to sign up for a service (POST request), and the server successfully creates a new user account, it responds with 201 Created.

  • 400 Bad Request: This status code indicates a general client error when the request sent to the server is invalid. An example is when a client submits a form with missing required fields, the server cannot process the request and responds with 400 Bad Request.

  • 401 Unauthorized: Used when authentication is required and has failed or has not been provided. For example, if a user tries to access a protected resource without proper authentication credentials, the server responds with 401 Unauthorized.

  • 403 Forbidden: This code indicates that the server understands the request but refuses to authorize it. A use case is when a user tries to access a resource they don’t have permission for, like an admin panel for regular users, resulting in a 403 Forbidden response.

  • 404 Not Found: Used when the requested resource is not found on the server. For instance, if a user tries to access a webpage that has been removed or never existed, the server responds with 404 Not Found.

  • 500 Internal Server Error: A generic error message for an unexpected condition encountered by the server. An example is when there’s a misconfiguration on the server or an error in the server-side script, leading to a 500 Internal Server Error response.

Classification of HTTP Status Codes

HTTP status codes are divided into five categories, each signifying a specific type of response and responsibility:

1xx (Informational): These codes indicate a provisional response, primarily acknowledging the receipt of a request. For example, 100 Continue suggests that the initial part of a request has been received and the client should continue with the request.

2xx (Success): This category signifies that the client's request was successfully received, understood, and accepted. A common example is 200 OK, which indicates a successful request.

3xx (Redirection): These codes inform the client that further action needs to be taken to complete the request, often involving redirection to another URI. 301 Moved Permanently is a typical example, indicating that the requested resource has been permanently moved to a new location.

4xx (Client Error): This group represents errors where the client seems to have erred. This means, the same request should't be tried again without modification or as is. 404 Not Found is one of the most recognizable status codes, indicating that the server cannot find the requested resource. Besides giving a bad user experience, these status codes can also hurt your SEO efforts, if you are hosting a website.

5xx (Server Error): These codes are used when the server fails to fulfill a valid request. Typically a server bug, unhandled scenario or something that is unexpected and the server failed. As a service owner, if you're experiencing 5xx server errors for your API services, you should immediately look at your cause and address it. The 500 Internal Server Error is a common code in this category, indicating a generic error when no more specific message is suitable. There are more specific codes. These error codes are considered for Rest API availability calculation.

REST API Best Practices with Respect to Status Codes

With the RESTful APIs, the HTTP status codes are bound tightly. These status codes not only convey the outcome of the client's request but also guide the client on the next steps to take. Here are some best practices for using HTTP status codes in REST APIs:

  • Choose Appropriate Status Codes: You should select the most specific status code for each response. This specificity helps clients understand exactly what happened with their request. For instance, use 201 Created for successfully created resources and 204 No Content when a request is successful but there's nothing to return.

  • Consistent Use of Status Codes: Apply status codes consistently across your API. Inconsistent use of status codes can lead to confusion and misinterpretation of the response by the client. E.g. using 200 OK for all success responses.

  • Use 2xx Series for Successful Operations: For all successful operations, use the 2xx series. Within this series, distinguish between different types of successes, like 200 OK for successful fetch operations, 201 Created for successful creation, and 202 Accepted for requests that have been accepted but are still processing.

  • Employ 4xx Series for Client Errors: Use 4xx series codes to indicate errors caused by the client. For example, 400 Bad Request for general client errors, 401 Unauthorized for authentication errors, and 404 Not Found when the requested resource does not exist.

  • Use 5xx Series for Server Errors: Utilize 5xx series codes for server-side issues. These indicate problems with the server that the client cannot resolve. For instance, 500 Internal Server Error for unexpected server issues and 503 Service Unavailable for temporary unavailability of the server.

  • Provide Clear Error Messages: In addition to the status code, provide a clear and descriptive error message in the response body. This message should give the client a clear understanding of what went wrong and, if possible, how to fix it.

  • Document Status Codes: Clearly document the status codes your API returns. This documentation should explain what each status code means in the context of your API and when each is used.

  • Avoid Overloading Status Codes: While it might be tempting to overload status codes with application-specific meanings, this can lead to confusion. Stick to the standard meanings as defined by the HTTP specification.

  • Handle Graceful Degradation: In cases where your API must change its behavior (e.g., deprecating endpoints), use status codes to indicate these changes gracefully, like 410 Gone for resources that used to exist but no longer do.

  • Monitor and Log Status Codes: Regularly monitor and log the status codes your API returns. This can help in identifying patterns, understanding the API's usage, and troubleshooting issues.

Using Beeceptor for Studying Status Codes

Beeceptor, an API mocking tool, is an excellent platform for understanding and experimenting with HTTP status codes. Here’s how to use Beeceptor for this purpose:

  1. Create a Mock API: Start by creating a mock API endpoint in Beeceptor.
  2. Configure Responses: Set up different mock rules to return various HTTP status codes. You can simulate scenarios like successful requests, client errors, and server errors.
  3. Test and Observe: Use an HTTP client to send requests to your Beeceptor endpoints. Observe the responses and status codes returned.
  4. Experiment with Scenarios: Modify the request parameters and headers to see how different inputs affect the status codes returned by your mock API.
  5. Learn Through Practice: Use this hands-on approach to understand the nuances of HTTP status codes and how they should be handled in real-world scenarios.

Additionally, explore readily available mock APIs like JSON Fake API and E-commerce API for quick testing.

401 Unauthorized vs 403 Forbidden

In web development, ensuring access control is essential in safely and efficiently managing APIs. The meanings of 401 Unauthorized and 403 Forbidden are sometimes confused. Nonetheless, both codes have to do with restricted resources, but they serve different purposes. In this article, we will explain the codes and instruct you on which one to use.

401 Unauthorized?

The response code for a request lacking valid authentication credentials from a client is referred to as the 401 Unauthorized status code. That being said, it means that before accessing the requested resource, it’s necessary for the server to authenticate itself to the client. If no credentials are provided or if wrong ones are given by the client, then what follows is a 401 status code.

When to Use 401 Unauthorized

Use 401 Unauthorized when:

  • No authentication details have been received yet from the client.
  • The authentication information supplied – username and password/token – is not valid/has expired.
  • There is no authorization header present in your requests like “Authorization.”

For instance, if an API demands Bearer token for access but this token has not been included in any request or is incorrect it will issue back a response having HTTP-code of Unauthorized (the most common case).

403 Forbidden?

The reason for using a 403 Forbidden status code when the server recognizes the request, the client has been authenticated, but the client does not have permission to access the requested resource. It means that in this case, a client is known while a server intentionally turns down fulfilling his or her request because of inadequate privileges.

When to Use 403 Forbidden

Use 403 Forbidden when:

  • Authenticated clientele lack sufficient permissions to reach given resources. • Server denies resource access irrespective of client’s authentication state. • Client’s access to resources is prohibited by any form of an access control system.

For instance, an authorized user may try accessing an admin only page without having adequate role. Even if one gets logged in and receive a response like ‘forbidden’ but still he/she does not have enough rights.

401 vs 403

Aspect401 Unauthorized403 Forbidden
Purpose401 indicates missing or invalid authentication.403 indicates lack of permission despite valid authentication.
When should server send this?When the client needs to provide valid credentials.When the client is authenticated but not authorized to access the resource.
What should the client do on receiving this?The client should provide or correct authentication details.The client should not retry, as access is denied.
ExampleAccessing a resource without a valid API token.Accessing a restricted admin area without sufficient privileges.

With the correct usage of 401 Unauthorized and 403 Forbidden status codes, you can make sure to avoid unwanted integration support tickets. The message clearly informs the clients on why they cannot gain access.

By correctly using 401 Unauthorized and 403 Forbidden status codes, you can ensure that your API communicates access issues clearly and helps clients understand the nature of the problem.

Next Post Previous Post
No Comment
Add Comment
comment url