+

Search Tips   |   Advanced Search

Implement content negotiation based on request parameters

With REST we 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. We 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.

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...

...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.


Related tasks

  • Use content negotiation to serve multiple content types in JAX-RS applications
  • Implement content negotiation based on URL patterns
  • Implement content negotiation based on HTTP headers

  • Web services specifications and APIs