+

Search Tips   |   Advanced Search

Implement content negotiation based on URL patterns

Representational State Transfer (REST) applications can return different representations of resources. Use content negotiation based on URL patterns 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 URL patterns. Content negotiation using URLs is the simplest type of content negotiation. This type of content negotiation always returns the same content with the same media type for a given URL.


Tasks

Use the URI defined in the @Path annotation to determine the content type for data returned to the server.

The following example illustrates content negotiation performed at the URL level. A request to /resources/myresource.xml returns the resource representation in XML. A request to /resources/myresource.json returns the resource representation in JSON.

@Path("/resources")
public class Resource {
    @Path("{resourceID}.xml")
    @GET public Response getResourceInXML(@PathParam("resourceID") String resourceID) {
        return Response.ok(/* entity in XML format */).type(MediaType.APPLICATION_XML).build();
    }

    @Path("{resourceID}.json")
    @GET
    public Response getResourceInJSON(@PathParam("resourceID") String resourceID) {
        return Response.ok(/* entity in JSON format */).type(MediaType.APPLICATION_JSON).build();
    }
}

We have implemented content negotiation using URL patterns 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 HTTP headers
  • Implement content negotiation based on request parameters
  • Web services specifications and APIs