I have a REST service that is exposed to iPhone and Android clients. Currently I follow the HTTP codes 200, 400, 401, 403, 404, 409, 500 etc.
My question is where is the recommended place to put the reason/description/cause of the error? Does it make more sense for the REST API to always have custom Reason in the header like so?
< HTTP/1.1 400 Bad Request - Missing Required Parameters.
< Date: Thu, 20 Dec 2012 01:09:06 GMT
< Server: Apache/2.2.22 (Ubuntu)
< Connection: close
< Transfer-Encoding: chunked
Or is it better to have it in the Response Body via JSON?
< HTTP/1.1 400 Bad Request
< Date: Thu, 20 Dec 2012 01:09:06 GMT
< Server: Apache/2.2.22 (Ubuntu)
< Connection: close
< Transfer-Encoding: chunked
< Content-Type: application/json
{ "error" : "Missing Required Parameters" }
Quoting from the HTTP specification for 400.x error codes:
It is best practice to include the error message as an entity in the body of the HTTP response - be it JSON, plain text, formatted HTML, or whatever other format you may want to utilize.
I always do both. I usually set the status message to something that the front end can display in a friendly manner to the user such as "409 - Could not add the new user, they already exist."
I then include the details of the error conditions in the body as JSON so that the UI developers can try to make intelligent choices about what to do.
It is better to have error details in the body. Furthermore, many (most / almost all, eg. WSGI) servers and clients do not support changing the name of the error code - treat them as fixed pairs (so eg. 400 is always "Bad Request" and not "Bad Request - You Forgot To Specify The User ID"). Even if they won't break, they won't care about your special name for specific error code.
The error does not belong in the body. It belongs in the Warning header.
Reference