Quick Answer

Content negotiation is a way for clients and servers to identify the best format for the resource being requested from a given URL.

Digging Deeper

With a typical website, the server normally returns HTML formatted data when a URL request is made. This makes sense since websites are generally expected to provide content that is capable of being rendered in a web browser. In these cases, the server just assumes that the client will be happy with HTML.

In web APIs, however, there might be a need to support multiple formats (or representations) of the same resource. Report data will often benefit from allowing more than one data format, as seen in PayPal's activity download page:

In these cases the client can negotiate with the server to get the most suitable format. Of course, the server has the final say in what it will return.

Negotiation is handled through one or more request header fields such as Accept, Accept-Charset, Accept-Encoding, and Accept-Language. The Accept header field pertains specifically to the media type being requested. A client would pass in the media type, or a special pattern to indicate options and preferences, and the server is expected to do its best to accommodate the request.

Here are some example Accept header field values:

ValueMeaning
text/htmlClient is requesting that the resource only be returned as HTML.
image/*Client is requesting that the resource be returned as an image, but the sub-type (i.e., JPEG, PNG, etc.) is up to the server.
image/jpg, image/png; q=.8, */*Client is requesting that the resource be returned as a JPEG image, but if that is not available then return as a PNG image. If that is not available then return any format that the server determines.

If the values listed in the Accept header field make it impossible for the server to accommodate, the server is expected to return a 406 Not Acceptable status. Therefore, clients might want to include a wildcard pattern (i.e., */*) in the value to ensure something is always returned.

  • No labels