HTTP Status Codes

API

“In computer programming, an application programming interface (API) is a set of subroutine definitions, protocols, and tools for building application software. In general terms, it is a set of clearly defined methods of communication between various software components”.

It is correctly defined, but still, the meaning is not much clear. So, let’s understand it with the help of one small example:

Consider an API as a waiter in a restaurant. Suppose you have a menu of your favorite food and the kitchen is the system where your order is made. But how do you take your order to the kitchen? Correct, you call a waiter, give him/her the order, which in turn take your order till the kitchen and then your order is made there and then finally, the waiter comes back with your delicious ordered food.

Thus, the API is very much similar to the waiter. API is the messenger that takes your order(waiter) and tells the system(kitchen) what to do (to prepare food) and in return gives back the response you asked for (waiter returns with the ordered food).

HTTP Status Codes

Every time you click on a link or enter an URL into the address bar, you send a request to a server. It makes some black box magic to create an answer for you where the first part is exactly an HTTP status code. The first three digits and a short phrase give a user (browser), crawler, or search robot an understanding of the server’s reaction to a query to a specified URL.

Example: 200 OK response code gives a clear message: ‘Everything is OK. You’re at the right place.

So, HTTP status codes are messages sent to the browser by a website server. The message will let the browser know if its request can be fulfilled. This request is usually for a copy of the website for the client.

A status code is a 3-digit number higher than 100 and smaller than 600 that is part of an HTTP response. The first digit defines the class of the status. A status code comes with a reason phrase. The code is for programmatic recognition the phrase is for humans to understand what happened.

Some APIs only use the most basic codes and define their own error signaling mechanisms on top of it, others want to make full use of HTTPs collection of codes to tell their clients what’s going on.

Still, Confused?….. Let’s go deep into it

Let’s dive deep into it.

Every status code has to follow these two rules – Status Code and Phrase. All codes are divided into 5 classes which differ by the first digit:

Status Classes

100 – 199 (Informational)

You won’t see these a lot. The server is saying, “Got it! I’m working on your request.”

These are informational status codes – they usually tell the client that the header part of the request has been received and the server will try to comply with a transmission demand of the client. These status codes basically act as transfer protocol-level information.
Example: Using a different protocol or telling the client that its request will fail before they start sending the body.

200 – 299 (Success)

This means “okay!” The server sends these when it’s successfully responding to your request.

These are the success codes. They tell the client that their request was accepted and processed.

In the case of asynchronous processing of a request, a status code of 202 is sent. This means that the request has been accepted because it met all validation requirements at the time of sending. It doesn’t mean the request was successfully processed.

 

300– 399 (Redirection)


This means “I can do what you want, but I have to do something else first.” You might see this if a website has changed addresses and you’re using the old one; the server might have to re-route the request before it can get you the resource you asked for.

These are redirection codes. They tell the client that the resource they are requesting isn’t available at the expected location anymore. This can have multiple reasons, be temporary or permanent, but the client has to issue a request to the new location.

400 – 499 (Client Error)


This means you probably made a mistake. The most famous is “404,” meaning “resource not found”: you asked for a resource or web page that doesn’t exist.
These are the client error codes. They are all about invalid requests a client sent to a server. There are several causes of this, timeouts, wrong URI, missing authentication, no record found, etc. This indicates that the client has sent an incorrect input.

500 – 599 (Server Error)

This means the server goofed up and can’t successfully respond to your request.

These are the server error codes. Often, they indicate problems with overwhelmed servers or unreachable servers behind proxies, but sometimes they can be directly related to client requests that trigger error exceptions on the server. These errors can be temporary or permanent. Usually, it’s best for the client to retry the same request.

Custom Classes:

Custom classes, that is, classes above 599 aren’t permitted but are used by some services anyway. For API designers, they are relevant as bad examples.

CRUD (Create, Read, Update, Delete)

CRUD

The CRUD model defines the most basic API actions for persistent storage. Create, read, update, and delete. They make up the lions-share (the largest part) of API endpoints.

 Let’s go deep into the status codes according to their requirements.

CREATE

The create action is usually implemented via HTTPs POST method. In RESTful APIs, these endpoints are used to create new resources or access tokens.

Status Codes

200 OK -It’s the basic status code to tell the client that everything went well

201 Created-The most fitting for Create operations. This code should signal backend-side resource creation and come along with a Location header that defines the most specific URL for that newly created resource. It’s also a good idea to include an appropriate representation of the resource or at least one or more URLs to that resource in the response body.

202 Accepted– Often used for asynchronous processing. This code tells the client that the request was valid, but its processing will finish sometime in the future. The response body should include an URL to the finished resource with some information about when it will be available, or an URL to some monitoring endpoint that tells the client when the resource is available.

303 See Other – Like the 202 code but using a Location header field in response to informing the client about the location of the created resource or an endpoint that lets the client check for the status of the creation process. Some clients follow the status codes of the Redirect class automatically. This code is usually only used for POST requests.

READ

The read action gets implemented via HTTPs GET method and is used to fetch resource representations. Asynchronous responses aren’t much of a thing here, because the reason for asynchronous processing is often that the resource doesn’t exist yet and has to be created, so it’s a create action anyway.

Status Codes

200 OK – Mostly read actions will be answered with a 200 OK status.

206 Partial Content – This code is useful for lists of content that are too big to be delivered in one response. It has to be used with a Range header field in the request. Usually, this header field defines the byte range the backend should send to the client, but the unit can be freely assigned as long as both sides understand it.

300 Multiple Choices – This redirect is used if there are multiple representations for one resource and the client (or its user) has to choose one of them

308 Permanent Redirect – This tells the client to use another URL to access the resource and not use the current URL anymore. It’s helpful when we have multiple endpoints for one resource, but don’t want to implement reading from all of them.

304 Not Modified – 304 not modified status code means that the website you’re requesting hasn’t been updated since the last time you accessed it. Typically, your browser will save (or cache) web pages so it doesn’t have to repeatedly download the same information. This is an attempt to speed up page delivery.

307 Temporary Redirect – When the URL to a resource could change in the future, the client should always ask for the current URL before accessing the real one.

UPDATE

An update can be implemented with an HTTP PUT or PATCH method. The difference lies in the amount of data the client has to send to the backend.
PUT requires the client to send an entire representation of a resource to update it. (Replace the old one with the new one).
PATCH requires the client only send parts of the representation of the resource to update it. (Add, update or delete these parts in the old version)

Status Codes

200 OK – This is the most appropriate code for most use cases.

204 No Content – A proper code for updates that don’t return data to the client, Example -When any update/delete request is sent.

202 Accepted – If the update is done asynchronous, this code can be used. It should include an URL to access the updated resource or an URL to check if the update has succeeded. It can also include an estimation of how long the update will take.

DELETE

The delete action can be implemented with the HTTP DELETE method.

Status Code

200 OK – Some people think a delete function of any kind should return the deleted element, so a representation of the deleted element can be included in the response body.

204 No Content – The most fitting status code for this case. It’s better to reduce traffic and simply tell the client the deletion is complete and return no response body (as the resource has been deleted).

202 Accepted – If the deletion is asynchronous and takes some time, which is the case in distributed systems, it can be appropriate to return this code with some information or URL to tell the client when it will be deleted.

API Changes

If our API lives long enough, sooner or later it will change its structure. It’s best practice to avoid breaking changes and the redirection class of status codes can help with this because some clients follow their Location header automatically.

Status Codes

307 Temporary Redirect – This is the right code if the resource could be available on a different URL in the future, but we want the current endpoint to control where the client is redirected to. This status code will let the client come back to the current URL for every request.

308 Permanent Redirect – This is the right code if the resource will now be available at a new URL and the client should directly access it via the new URL in the future. The current endpoint can’t control the clients’ behavior after the request and a subsequent redirect if the resource URL changes again have to be issued from the new URL.

 

Errors

The next important part of an API is its errors. Many API frameworks use 500 and 404 status codes by default when something went wrong, but depending on the situation, often there are more descriptive ones.

500 means Internal Server Error, which can be anything from system failure to checking the reachability of the third-party service the backend wanted to call.

If the client did something wrong then we would expect a 400-499 status code.
404 means Not Found. This can be because of a wrong URL used by the client to some endpoint not being set up right on the backend or the resource doesn’t exist.

As we see the 404 is a client error status code, but it could very well be that we did something wrong on the backend.
Example – We are requesting something that doesn’t exist in our system.

Status Codes

404 Not Found – This is the most natural of responses and should be used in the case that the requested URL was wrong or a resource was not found.

405 Method Not Allowed -In many frameworks we define the URL along with the HTTP method.

We have several built-in methods to make HTTP requests to specified URI using GET, POST, PUT, PATCH, or HEAD requests. An HTTP request is meant to either retrieve data from a specified URI or push data to a server. It works as a request-response protocol between a client and server.

410 Gone – This is like 404 but we know that the resource existed in the past, but it got deleted or somehow moved, and we don’t know where.

406 Not Acceptable – The URL exists, but the backend can’t send a representation the client will accept. 406 Not Acceptable client error response code indicates that the server cannot produce a response matching the list of acceptable values defined in the request’s proactive content negotiation headers and that the server is unwilling to supply a default representation.

414 Request-URI Too Long – This is sometimes the case when the endpoint is right, and the resource exists, but the query makes the URL too long to be interpreted.

429 Too Many Requests – When a server detects excessively high activity from one user during a period of time, it responds with a 429 code.
Respect your server, it’s almost as busy as Google – everybody asks it about something.

308 Permanent Redirect -This would be the right code if we know that a resource has moved to a different URL and we can tell the client about it.

307 Temporary Redirect – Same as 308, but we don’t know if the resource will be back on the original URL or another different URL in the future.

500 Internal Server Error – This issue may describe a lot of problems on your server. It’s something unpredictable, and the reason can’t be easily detected, so it’s not marked with any other exact codes.

Example: Any component failure, any connection failure, bad coding, any unexpected error.

501 Not Implemented – 501 code is returned, which means that the method used to fulfill the request does not work or was not found on the server.
Causes:
1)Viruses or malware
2)Server overload
3)Expired server software

Like 405, but the method is missing for all resources on the backend.

502 Bad Gateway – 502 Bad Gateway Error occurs when you try to visit a web page, but one web server gets an invalid response from another. Usually, the problem is on the website itself, and there’s nothing you can do. This error occurs because of a problem with your computer or networking equipment. One server on the internet received an invalid response from another server.

503 Service Unavailable – It’s like a vacation for your server. Usually, it’s caused by temporary maintenance or a high load.

504 Gateway Timeout – It indicates that the server while acting as a gateway or proxy, did not get a response in time from the upstream server that it needed in order to complete the request

No Permissions

Often clients can’t access every resource on the backend, so we need a way to tell them about it.

Status Codes

401 Unauthorized – The client hasn’t authorized itself to the backend yet and the server may give it access after that has happened.

403 Forbidden – The client has authorized or doesn’t need to authorize itself, but still has no permission to access the resource.

404 Not Found – If 401 or 403 is the case, but the backend doesn’t want to tell the client that the resource exists for security reasons.

Conclusion

The HTTP creators thought about many status codes when designing it and even added a bunch of new ones over the years. If they’re used correctly they can help to improve developer experience greatly by leveraging automatic redirect follows of clients and explaining what happened more clearly. Sometimes there are multiple codes we could use for one particular case; the important thing is that we keep our usage consistent over the whole API surface.

References:

  1. https://restfulapi.net/http-status-codes/
  2. https://www.quora.com/What-are-HTTP-Status-codes-used-in-standard-REST-API-Responses
  3. https://netpeaksoftware.com/blog/how-to-check-http-status-code
  4. https://www.moesif.com/blog/technical/api-design/Which-HTTP-Status-Code-To-Use-For-Every-CRUD-App/
  5. https://kinsta.com/blog/http-status-codes/
  6. https://www.google.com/
  7. https://rockcontent.com/blog/error-501-not-implemented/
  8. https://www.howtogeek.com/356389/what-is-a-502-bad-gateway-error-and-how-can-i-fix-it/

Image courtesy of Kusum Rawat | APISetu | Blog

Authors

6 thoughts on “HTTP Status Codes

Leave a Reply

Your email address will not be published. Required fields are marked *

error: Content is protected !!