What HTTP Status Code to Return

This is the fifth step in Design Restful API. In this post, we will learn what HTTP status code to return from REST API
In the previous post, we learned - 
When the client raises a request to the server through an API, the client should know the feedback, whether it failed, passed or the request was wrong. 

HTTP response codes are three-digit numbers that provide information about the status of a request made to a web server. They help to indicate whether the request was successful, and if not, why not.

Let's discuss the important categorization of HTTP codes.

2xx (Success category)

These status codes represent that the requested action was received and successfully processed by the server.
Here are some of the commonly used 2xx category status codes:

200 OK 

The request has succeeded, meaning depends on the request method (GET, HEAD, POST, PUT, DELETE, OPTIONS, TRACE).

201 Created

The server has completed the request, creating one or more new resources identified by the Location header or target URI.
For example, creating a new instance, using the POST method, should always return a 201 status code.

202 Accepted

The server has accepted the request for processing but is not finished yet, intended for batch processing.

203 Non-authoritative Information

The request was successful, but the transforming proxy changed information before sending it to the browser.

204 No Content

The server has completed the request but there is no additional content to send in response.

The DELETE REST API can be a good example of this. 
For example, The API DELETE /companies/43/employees/2 will delete employee 2 and in return, we do not need any data in the response body of the API, as we explicitly asked the system to delete it. If there is any error, like if employee 2 does not exist in the database, then the response code would not be of the 2xx Success Category but around the 4xx Client Error category.

205 Reset Content 

The server has fulfilled the request and the user should reset the document view to its original state. 

3xx (Redirection Category)

Here are some of the commonly used 3xx category status codes:

300 Multiple Choices

The server has multiple options for the resource that the client can choose from.

301 Moved Permanently

The resource has been permanently moved to a new URI, future references should use the new URI.

302 Found

The resource has been temporarily moved to a new URI, future references should use the original URI.

304 Not Modified

The resource has not been modified since last requested, can use a cached copy of the resource.

304 Not Modified indicates that the client has the response already in its cache. And hence there is no need to transfer the same data again.

4xx (Client Error Category)

These status codes represent that the client has raised a faulty request.

400 Bad Request

The request could not be understood by the server due to malformed syntax.

401 Unauthorized

Requires user authentication to access resources.

403 Forbidden

403 Forbidden indicates that the request is valid and the client is authenticated, but the client is not allowed access to the page or resource for any reason. 

For example, sometimes the authorized client is not allowed to access the directory on the server.

404 Not Found

The requested resource could not be found on the server.

405 Method Not Allowed

Request method not supported by resource.

406 Not Acceptable

The resource is only capable of generating a response that is not acceptable according to Accept headers.

408 Request Timeout

The resource is only capable of generating a response that is not acceptable according to Accept headers.

413 Payload Too Large

The request is larger than the server is able to process.

415 Unsupported Media Type

The request body is in a format that the server does not support.

429 Too Many Requests

The client has sent too many requests in a given amount of time.

5xx (Server Error Category)

500 Internal Server Error 

The server encountered an unexpected condition that prevented it from fulfilling the request.

501 Not Implemented 

The server does not support the functionality required to fulfill the request.

502 Bad Gateway

The server received an invalid response from an upstream server while attempting to fulfill the request.

503 Service Unavailable

The server is currently unable to handle the request due to a temporary overload or maintenance.

504 Gateway Timeout

The server did not receive a timely response from an upstream server while attempting to fulfill the request.

Case Study 1

An appropriate HTTP status code is set in the response to be returned to the client. In this case study, let's take Employee Management System(EMS) application. Let's analyze the EMS application and find out different resource operations. 

Consider we have an Employee entity so let's Identify Resources from the Employee entity using step 1After identifying the REST resources let's design the URL for REST resources by using step 2.

Let's apply below HTTP status code guidelines to return the HTTP status code
  • When the request is successful, an HTTP status code indicating success or transfer (2xx or 3xx system) is sent as a response.
  • When the cause of request failure lies on the client side, an HTTP status code indicating client error (4xx system) is sent as the response. When a client is not responsible for request failure, however, when the request may be successful through a re-operation by the client, it is still considered as client error.
  • When the cause of request failure lies on the server side, an HTTP status code indicating server error (5xx system) is sent as the response.
Examples:

Method: Use the GET method to retrieve employee objects by id
Resource URL : /api/v1/employees/100
Return HTTP Status Code: 200 OK
-----------------------------------------------------------------------------------
Method: Use the GET method to retrieve employees.
Resource URL : /api/v1/employees
Return HTTP Status Code: 200 OK
-----------------------------------------------------------------------------------
Method: Use the POST method to post an employee object
Resource URL : /api/v1/employees
Return HTTP Status Code: 201 Created
-----------------------------------------------------------------------------------
Method: Use PUT method to update the employee object by id and pass the employee object as JSON
Resource URL : /api/v1/employees/100
Return HTTP Status Code: 204 No Content
-----------------------------------------------------------------------------------

Case Study 2

REST APIs for User Management Application - Following five REST APIs and their status codes for the User resource:

Conclusion

In this post, we learned what HTTP status code to return from REST API.  It is important to return the appropriate HTTP status code in the response to be to the client.

Complete List of HTTP Status Codes

Here is the complete list of HTTP status codes for your reference.

1XX Informational 

  • 100 (Continue)
  • 101 (Switching Protocols) 
  • 102 (Processing) 
  • 103 (Early Hints)

2XX Successful 

  • 200 OK
  • 201 Created
  • 202 Accepted
  • 203 Non-Authoritative Information
  • 204 No Content
  • 205 Reset Content
  • 206 Partial Content
  • 207 Multi-Status
  • 208 Already Reported
  • 226 IM Used

3XX Redirection 

  • 300 Multiple Choices
  • 301 Moved Permanently
  • 302 Found 
  • 303 See Other
  • 304 Not Modified
  • 305 Use Proxy
  • 306 Switch Proxy
  • 307 Temporary Redirect
  • 308 Permanent Redirect

4XX Client Error 

  • 400 Bad Request
  • 401 Unauthorized
  • 402 Payment Required
  • 403 Forbidden
  • 404 Not Found
  • 405 Method Not Allowed
  • 406 Not Acceptable
  • 407 Proxy Authentication Required
  • 408 Request Timeout
  • 409 Conflict
  • 410 Gone
  • 411 Length Required
  • 412 Precondition Failed
  • 413 Payload Too Large
  • 414 URI Too Long
  • 415 Unsupported Media Type
  • 416 Range Not Satisfiable
  • 417 Expectation Failed
  • 418 I’m a Teapot
  • 421 Misdirected Request
  • 422 Unprocessable Entity
  • 423 Locked
  • 424 Failed Dependency
  • 425 Too Early
  • 426 Upgrade Required
  • 428 Precondition Required
  • 429 Too Many Requests 
  • 431 Request Header Fields Too Large
  • 451 Unavailable for Legal Reasons

5XX Server Error

  • 500 Internal Server Error
  • 501 Not Implemented
  • 502 Bad Gateway
  • 503 Service Unavailable
  • 504 Gateway Timeout
  • 505 HTTP Version Not Supported
  • 506 Variant Also Negotiates
  • 507 Insufficient Storage
  • 508 Loop Detected
  • 510 Not Extended
  • 511 Network Authentication Required

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments