Reputation: 16625
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.
Upvotes: 8
Views: 8199
Reputation: 9344
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.
Upvotes: 12
Reputation: 173662
Don't bother.
There will be cases whereby consumers of your service wouldn't bother to set this header, e.g. when using cURL
or file_get_contents()
in PHP.
If your API documentation states that your service only supports JSON output, that should be good enough.
You could also work with extensions to enforce the format, e.g. /path/to/resource.json?a=b
or /path/to/resource.xml?a=b
for JSON and XML respectively.
In the case that you want to support multiple output formats and the Accept
request header value is non-conclusive, you should define a default output format.
Upvotes: 4