1. API Clients support multiple formats
A REST API can return the resource representation in many formats – to be more specific MIME-types. A client application or browser can request for any supported MIME type in HTTP Accept header.
Accept header can have multiple values in form of comma-separated values.
For example, an
Accept header requesting for
application/xml formats can be set as:
Accept : text/html,application/xml
2. The ‘q’ Parameter
Sometimes clients may want to set their preferences when requesting multiple
MIME types. To set this preference,
q parameter (relative quality factor) is used.
q parameter can be from 0 to 1. 0 is the lowest value (i.e. least preferred) and 1 is the highest (i.e. most preferred).
A sample usage can be:
Accept : text/html, application/xml;q=0.9, */*;q=0.8
In the above example, the client is indicating to the server that it will prefer to have the response in text/html format, first.
If the server does not support text/html format for the requested resource then it shall send
application/xml format. If none of both formats are available, then send the response in whatever format it support (
- One of the benefit of the ‘q’ parameter is to minimize the client-server interactions, which could have happened due to failed content negotiations.
- It also allows clients to receive content types of which they may not be aware, an asterisk “*” may be used in place of either the second half of MIME type value or both halves.
3. According to HTTP Specs
Here’s how the HTTP spec defines it:
Each media-range MAY be followed by one or more accept-params, beginning with the “q” parameter for indicating a relative quality factor. The first “q” parameter (if any) separates the media-range parameter(s) from the accept-params.
Quality factors allow the user or user agent to indicate the relative degree of preference for that media-range, using the ‘q’ value scale from 0 to 1.
The default value is 1.
If there are two MIME types for the same
q value, then a more specific type, between both, wins.
For example, if both
*/* had a preference of 0.9 then
application/xml will be served by the server.
Acceptheader field is present, then it is assumed that the client accepts all media types.
Acceptheader field is present, and if the server cannot send a response which is acceptable according to the combined
Acceptfield value, then the server SHOULD send a
406 (not acceptable)response.