Implementing content negotiation based on request parameters

Representational State Transfer (REST) applications can return different representations of resources. You can use content negotiation based on request parameters to determine the content format that is used to exchange data between servers and clients.

About this task

Resources can represent data in different formats. You can implement content negotiation based on URLs, request parameters, or HTTP headers. This task describes content negotiation based on request parameters for receiving different data formats.

You can use request parameters, such as query parameters, to indicate the type of content for the server to return. For example, if the parameter value is xml, the server is expected to return XML content. Similarly, if the parameter value is json, the server is expected to return JSON content.

Using request parameters reduces the numbers of URLs, versus implementing content negotiation based on URL patterns. However, this method requires the usage and parsing of a parameter in the resource method implementation.

Procedure

Use a parameter to determine the content type for data that the server returns.

In the following example, XML and JSON data formats are acceptable, and the format is specified by a query parameter. By default, XML is returned. A request to /resources/resource?format=json results in the JSON format being returned from the server; for example:

@Path("/resources")
public class Resource
{
    @Path("{resourceID}")
    @GET
    public Response getResource(@PathParam("resourceID") String resourceID, @QueryParam("format") String format)
    {
        if (format == null || "xml".equals(format)) {
            return Response.ok(/* entity in XML format */).type(MediaType.APPLICATION_XML).build();
        } else if ("json".equals(format)) {
            return Response.ok(/* entity in JSON format */).type(MediaType.APPLICATION_JSON).build();
        }
        return Response.notAcceptable(Variant.mediaTypes(MediaType.APPLICATION_XML_TYPE, MediaType.APPLICATION_JSON_TYPE).add().build()).build();
    }
}

Results

You have implemented content negotiation using parameters to determine the formats for resources that represent data.