I am writing a web service that accepts only json, and also outputs only json.
So I need to return the appropriate status code if any other format is requested.
It appears that I have two choices:
- 406 - Not Acceptable
- 415 - Unsupported Media Type
It would be great if someone could enlighten me as to the semantics of the two codes.
406 is returned by the server when it can't respond based on accepting the request headers (ie they have an Accept header which states they only want XML).
415 is returned by the server when the entity sent in a request (content in a POST or PUT) has an unsupported mediatype (i.e. they sent XML).
so.. 406 when you can't send what they want, 415 when they send what you don't want.
Hope that helps!
To quote RFC2616:
406 Not Acceptable
The resource identified by the request
is only capable of generating response
entities which have content
characteristics not acceptable
according to the accept headers sent
in the request.
When a client queries your service, check what Accept*
headers it sent; if it doesn't match application/json
(or a wildcard, e.g. */*
), return this. The response should indicate "we only serve JSON here".
415 Unsupported Media Type
The server is refusing to service the
request because the entity of the
request is in a format not supported
by the requested resource for the
requested method.
Just returning 415 Unsupported Media Type
should be the minimum response for "the client has sent something that's not JSON, can't work with that"; not sure if there's a header to indicate "you need to send JSON"
406 is used when the client requests a response in an unsupported content type (in your case, anything other than JSON) using the Accept header. 415 on the other hand is used when the client POSTs or PUTs data in an unsupported content type.
In a nutshell: use 406 if can't output in the expected format and use 415 if you don't support the input format.
See RFC 2616 for their definitions: 406 and 415
RFC2616 helps you!
http://www.rfc2616.com/#10.4.7
http://www.rfc2616.com/#10.4.16
I'd pick the 415, it suits your description quite well.
Edit: Oh. IC. "the entity of the request is in a format not supported by the requested resource". So if you have a request with content and that content has wrong type, you should throw 415 -response.