JAX-RS Response Handling

by bhagyashree kolge

Introduction

The JAX-RS specification for building RESTful services gives clear directions for handling API responses. Some specific annotations and classes are available for this task. Let’s have a look at how the responses are handled at the server-side of JAX-RS web services.

Building a JAX-RS Response

By default, JAX-RS supports response messages of common Java types. These responses can be either in plain text, XML or JSON format. JAX-RS provides javax.ws.rs.core.Response class for creating responses.

The below code sample will produce a response in the plain-text format.

@GET

  @Path(“color”)

  @Produces(TEXT_PLAIN)

  public Response getTextileColor()

  {

    if (color) {

      return Response.ok().build();

    }

    // return 404 Resource not found error.

    return Response.status(Response.Status.NOT_FOUND).build();

  }

}

  Normally a response will contain a resource that the client is requesting from the server. The resource representation in java must be marshaled and converted into the media type specified in the REST API request. A POJO [Plain Old Java Object] is converted into REST response format through the process as given below:

Response Entity

The response entity is also referred to as ‘payload’ or ‘message body’. While using JAX-RS, response entities are mapped to and from java types by Entity Providers that implement the JAX-RS interface MessageBodyWriter.

Message Body Writer

The JAX-RS Message Body Writer converts java types to a stream. There are three main methods in this class. They are isWritable(), getSize() and writeTo() which can be overridden while implementing our logic.

Successful Responses

Successful responses are sent along with corresponding HTTP codes. They range from 200 to 399. The JAX-RS response specifications are similar to that of HTTP specifications for GET, PUT, POST, DELETE methods. If an API request is successful and the response contains a message body, then the status code will be 200, ‘OK’. Otherwise, it will be a 204, ‘No Content’ message in the response status.

Error Responses

Error response codes range from 400 to 599. These are used based on failure cases. By examining the error code that is returned to the client, we can understand the type of issue faced at the server-side.

@Produces Annotation

The @Produces annotation mentions the media types that a resource can produce and set back to the client. If no method can produce the resource in the specified media type, the REST library will send a “406 Not Acceptable” error to the client.

Summary

In general, responses are built according to the request type. There are classes in JAX-RS that help in the process of building responses. The responses are handled with specific HTTP codes that are sent along with the responses. These codes help the client application to understand the server-side better.