Rest error message in HTTP Header or Response Body?
Asked Answered
W

3

98

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" }
Willman answered 20/12, 2012 at 1:27 Comment(1)
Nowadays, it is a common practice to add custom headers, such as 'X-HTTP-Error-Description: Missing required parameters'.Gravitative
D
119

Quoting from the HTTP specification for 400.x error codes:

The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. These status codes are applicable to any request method. User agents SHOULD display any included entity to the user.

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.

Devora answered 20/12, 2012 at 1:33 Comment(0)
C
28

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.

Cannot answered 20/12, 2012 at 1:31 Comment(0)
G
4

The error does not belong in the body. It belongs in the Warning header.

The Warning general HTTP header contains information about possible problems with the status of the message.

Reference

Gomulka answered 20/8, 2018 at 17:37 Comment(2)
Would be nice to use an "official" header for this. However, Warning, as the name suggests, is not for errors. The RFC (7234) says: >The use of a warning, rather than an error status code, distinguishes these responses from true failures.Rakia
Note: The Warning header is soon to be deprecated; see Warning (github.com/httpwg/http-core/issues/139) and Warning: header & stale-while-revalidate (github.com/whatwg/fetch/issues/913) for more details.Counterscarp

© 2022 - 2024 — McMap. All rights reserved.