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 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
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:
When a client queries your service, check what
Accept*
headers it sent; if it doesn't matchapplication/json
(or a wildcard, e.g.*/*
), return this. The response should indicate "we only serve JSON here".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"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.
Accept
header was sent you cannot fullfill.Content-Type
is sent you cannot use.