Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP response for an unacceptable Accept header

Tags:

rest

http

api

My RESTFul API can only respond JSON-encoded data (i.e. all my headers have Content-Type: application/json). What should I return, if the request has an Accept header that does not allow JSON (for example, Accept: text/html)? Should I just return a 400 Bad Request with an explanation in the body, or is there a more specific status code for this exception?

Note that this is different from unsupported request content-types.

like image 331
Attila O. Avatar asked Feb 21 '13 23:02

Attila O.


People also ask

What does HTTP 406 mean?

The HyperText Transfer Protocol (HTTP) 406 Not Acceptable client error response code indicates that the server cannot produce a response matching the list of acceptable values defined in the request's proactive content negotiation headers, and that the server is unwilling to supply a default representation.

What does */* mean in Accept header?

14.1 Accept The asterisk "*" character is used to group media types into ranges, with "*/*" indicating all media types and "type/*" indicating all subtypes of that type. The media-range MAY include media type parameters that are applicable to that range.

When should I use HTTP 406?

406 happens when the server cannot respond with the accept-header specified in the request. In your case it seems application/json for the response may not be acceptable to the server.

Which HTTP response header can be used to raise an error?

The Warning HTTP header contains information about possible problems with the status of the message. More than one Warning header may appear in a response.


1 Answers

If you want to be semantically correct:

If the request is HTTP/1.0:

a 406 Not Acceptable is the correct thing to return, as the client may not be able to handle a response that isn't of the type requested.

in HTTP/1.1, that's still the "right" thing to do, but there are exceptions,

From RFC 2616 Sec 10.4.7

 Note: HTTP/1.1 servers are allowed to return responses which are
      not acceptable according to the accept headers sent in the
      request. In some cases, this may even be preferable to sending a
      406 response. User agents are encouraged to inspect the headers of
      an incoming response to determine if it is acceptable.

In truth, the likelihood of it mattering is pretty low, as @Jack has mentioned. I'm only including this answer in the interests of completeness.

like image 59
Kylar Avatar answered Sep 21 '22 23:09

Kylar