Implementing content negotiation based on HTTP headers
Representational State Transfer (REST) applications can return different representations of resources. You can use content negotiation based on HTTP Accept headers 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 HTTP Accept headers for sending and receiving different data formats.
When a web browser makes a request, it sends information about what it is looking for to the server in headers. One of these headers is the Accept header. The Accept header tells the server what formats or MIME types that the client is looking for. You can use the HTTP Accept headers to determine the content format used to exchange data.
While the Accept header is not as visible as URLs or parameters, this header is a more flexible method of handling content negotiation. You can also use the HTTP Accept, Accept-Charset, Accept-Language, and Accept-Encoding headers to determine the type of content that is returned from the server.
Using HTTP Accept headers, you can assign degrees of quality to acceptable responses. For example, a client can indicate XML is the preferred response content type. However, if XML is not available, the client can accept JSON or plain text for the format.
For example, if the Accept header contains a value such as application/json; q=1.0, text/xml;q=0.5, application/xml;q=0.5, this value indicates that JSON is preferred but XML is acceptable as well.
In other methods of content negotiation, typically only one preferred response type exists. However, you can use the HTTP Accept headers to inform the service of all the possible types that are acceptable to the client in one request. Furthermore, the HTTP Accept and its related headers are part of the HTTP standard.
It is important to consider the following aspects when implementing content negotiation using HTTP headers. Some clients might send incorrect values and some services might not respect the Accept HTTP headers. Also, processing all the HTTP headers and calculating the optimal response is not as straightforward as requesting content based on a URL or a request parameter.
Procedure
Results
You have implemented content negotiation using Accept headers to determine the formats for resources that represent data.