HTTP Status Codes for REST API

LinkedIn Tweet Facebook
HTTP Status Codes for REST API

Introduction

HTTP Status codes help categorize the response. Sometimes they are self-explanatory (e.g. 404) and sometimes they are backed by information (e.g. 201). A REST API MUST implement these status codes well to convey the right information to its clients. Correct status codes help client app developers handle responses better. Here will focus more on 4XX Status Codes for communicating errors with the rest clients.

2XX Content

Browsers generate a success indicator for the 2XX status code. So 2XX status codes should be used specify a successful request.

When the server has a long operation to be performed, it responds with 202. But since REST is stateless, it cannot respond to the request later. The client, therefore after a certain interval, requests again for the same resource and gets the data intended for request with 202 response. This follow-up request is replied with status 203 by the server.

3XX Redirect

The REST API developer should maintain old resources, in case he is migrating to new ones. 3XX series codes are displayed as errors in browser console and should be used to indicate resource relocation.

4XX Status Codes (Client Errors)

When the client makes a mistake, the server should notify the client of 4XX error. The most popular being 404. When the server cannot find the resource the client requested. Browsers show errors in their console for 4XX series, even when they necessarily are errors. For example, when the resource is deleted, the server SHOULD return 410 instead of 200 stating that the resource has been deleted.

Server throws 400 when the user is sending an invalid request. Something that's not even HTTP request. For example, the client is sending just plaintext, with no reference to method or protocol. It throws 422 when Content-Type header says application/json, but XML is being sent.

There are several other 4XX status codes that can be used as well like 407 proxy authentication required, 416 requested range not satisfiable, 417 expectation failed but they are less common.

These client codes are most common and best used by REST APIs to convey client errors. There are other status codes in 4XX series and you can roll out your own for something specific.

5XX Server Errors