Implementing content negotiation based on URL patterns

Representational State Transfer (REST) applications can return different representations of resources. You can use content negotiation based on URL patterns 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 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.

Procedure

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();
    }
}

Results

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