Using HTTP status codes in RESTful web APIs

Currently, there are over 75 status codes to report the statuses of various operations. The HTTP status codes are classified into the following five categories:

  • 1xx Informational: This code indicates informational messages
  • 2xx Successful: This code indicates successful processing of the requests
  • 3xx Redirection: This code indicates that an action needs to be taken by the client to complete the request
  • 4xx Client error: This code indicates a client error
  • 5xx Server error: This code indicates a server failure in fulfilling the request

It is always recommended to return the appropriate status codes in response to a RESTful web API call. The status code present in the response helps the client take an appropriate action, depending upon the status of the operation. The following table summarizes the commonly used HTTP status codes to describe the status of a RESTful web API call:

Commonly used HTTP status codes

Description

200 OK

This status indicates a successful GET, PUT, PATCH, or DELETE operation. This status can be used for POST if an existing resource has been updated.

201 Created

This status is generated in response to a POST operation that creates a new resource.

204 No Content

This code tells that the server has processed the request but not returned any content. For example, this can be used with the PUT, POST, GET, or DELETE operations if they do not result in any result body.

304 Not Modified

This code tells the client that it can use the cached resource that was retrieved in the previous call. This code is typically used with the GET operation.

400 Bad Request

This code indicates that the request sent by the client was invalid (client error) and could not be served. The exact error should be explained in the response entity body payload.

401 Unauthorized

This code indicates that the REST API call requires user authentication. The client can take the necessary steps for authentication based on this response status.

403 Forbidden

This code indicates that the caller (even after authentication) does not have an access to the requested resource.

404 Not Found

This code indicates that the requested resource is not found at this moment but may be available again in the future.

405 Method Not Allowed

This code indicates that the HTTP method requested by the caller is not supported by the resource.

406 Not Acceptable

This code indicates that the server does not support the required representation. For example, this can be used in response to the GET, PUT, or POST operations if the underlying REST API does not support the representation of the resource that the client is asking for.

409 Conflict

This code indicates that the request could not be completed due to some general conflict with the current state of the resource. This response code makes sense where the caller is capable of resolving the conflict by looking at the error details present in the response body and resubmitting the request. For example, this code can be used in response to PUT, POST, and DELETE if the client sends an outdated resource object to the server or if the operation results in the duplication of resources.

410 Gone

This code indicates that the resource identified by this URI is no longer available. Upon receiving a 410 status code, the caller should not request the resource again in the future.

415 Unsupported Media Type

This code indicates that the entity media type present in the request (PUT or POST) is not supported by the server.

422 Unprocessable Entity

This code indicates that the server cannot process the entity present in the request body. Typically, this happens due to semantic errors such as validation errors.

429 Too Many Requests

This code indicates that the client has sent too many requests in a given time, which results in the rejection of requests due to rate limiting. Note that rate limiting is used for controlling the rate of traffic sent or received by a network interface controller.

500 Internal Server Error

This code indicates that the server encountered an unexpected error scenario while processing the request.

 

When an operation fails on a resource, the RESTful web API should provide a useful error message to the caller. As a best practice, it is recommended to copy the detailed exception messages into the response body so that the client can take appropriate actions. By default, all JAX-RS containers intercept all exceptions thrown during the processing of the REST APIs and process them in their own way. However, you can provide your own javax.ws.rs.ext.ExceptionMapper to override the default exception handling offered by the JAX-RS runtime. We have discussed this topic in detail under the Mapping exceptions to the response message using ExceptionMapper section in Chapter 4, Advanced Features in the JAX-RS APIs. The following code snippet illustrates how you can build an ExceptionMapper provider for handling javax.validation.ValidationException. The ValidationException errors are typically thrown by the framework when the bean validation rules that you set on the model class fail:

//Imports are removed for brevity 
@Provider 
// A provider that maps Java exceptions to a Response 
public class ValidationExceptionMapper implements ExceptionMapper<ValidationException> { 
 
    // Map validation exception to a Response 
    @Override 
    public Response toResponse(ValidationException exception) { 
        //Set 400 Bad Request status and error message entity 
        if (exception instanceof ConstraintViolationException) { 
            return buildResponse(unwrapException(( 
                ConstraintViolationException) exception), 
                MediaType.TEXT_PLAIN, Status.BAD_REQUEST); 
        }else{ 
        return buildResponse(unwrapException(exception),  
            MediaType.TEXT_PLAIN, Status.BAD_REQUEST); 
        } 
    } 
    //Build response obj containing error message as entity 
    protected Response buildResponse(Object entity, 
        String mediaType,  
        Status status) { 
        ResponseBuilder builder = Response.status(status). 
            entity(entity); 
        builder.type(MediaType.TEXT_PLAIN); 
        builder.header("validation-Error", "true"); 
        return builder.build(); 
    } 
  //unwrapException() method definition is removed for brevity 
} 
The complete source code for this example is available at the Packt website. You can download the example from the Packt website link mentioned at the beginning of this book in the Preface section. In the downloaded source code, see the Java source file called com.packtpub.rest.ch8.service.exception.ValidationExceptionMapper, available in the rest-chapter8-jaxrs/rest-chapter8-service project.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.54.245