Implement content negotiation based on request parameters
Representational State Transfer (REST) applications can return different representations of resources. Use content negotiation based on request parameters to determine the content format used to exchange data between servers and clients.
Resources can represent data in different formats. 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.
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.
Use 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.
Tasks
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(); } }
We have implemented content negotiation using parameters to determine the formats for resources that represent data.
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