Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rest error message in HTTP Header or Response Body?

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" } 
like image 593
James Cowhen Avatar asked Dec 20 '12 01:12

James Cowhen


People also ask

How do I send HTTP error messages in REST API?

The most basic way of returning an error message from a REST API is to use the @ResponseStatus annotation. We can add the error message in the annotation's reason field. Although we can only return a generic error message, we can specify exception-specific error messages.

Is HTTP response code a header?

HTTP headers The status code is just part of the full HTTP response that a server sends to a client. Additional information is sent across with the status code. The full response of a status code plus additional information is called the HTTP header.

What is HTTP header and HTTP body?

The start-line and HTTP headers of the HTTP message are collectively known as the head of the requests, whereas its payload is known as the body.


1 Answers

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.

like image 138
Perception Avatar answered Sep 20 '22 21:09

Perception