8

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.

Community
  • 1
  • 1
Attila O.
  • 13,553
  • 9
  • 51
  • 82

2 Answers2

11

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.

Kylar
  • 7,966
  • 6
  • 41
  • 72
4

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.

Ja͢ck
  • 161,074
  • 33
  • 239
  • 294
  • 1
    So you say just return the usual response with `Content-Type: application/json` anyway? – Attila O. Feb 21 '13 at 23:40
  • Ok, that's simple enough. What would you do, on the other hand, if the API would support both JSON and something else, say Bencode (`application/x-bencode`), but the request specified something third, say, `Accept: text/xml`? (I know this is not part of my original question.) – Attila O. Feb 21 '13 at 23:44
  • @AttilaO. I've updated my answer to be more canonical in regards to your question. – Ja͢ck Feb 21 '13 at 23:50
  • Very nice. I know some APIs like to use the extension to define a response format, but that's less flexible than the header (think `Accept: application/json, text/xml`). Defining a *default* output format makes the most sense imo, thanks. – Attila O. Feb 21 '13 at 23:53
  • @AttilaO. It may be less flexible, but in many cases: "explicit" > "implicit" :) – Ja͢ck Feb 21 '13 at 23:54