What is the correct way to return a specialized HTTP response?

141 views Asked by At

Let's say that in my RESTful interface I require the client to include some special header, just to indicate it's an authorized client. (Trust me on this; it's a requirement of the project.) If the HTTP request contains an incorrect value in this header, the server needs to send back an HTTP response that the client can recognize that it sent an unsupported value in the header.

What's the appropriate way to send back this information using HTTP?

  • I could send back a 400 Bad Request response, but how do I tell the client what the problem was exactly? The obvious option is to include some message in the body of the response. But (besides issues of i18n) is it really a good idea for the client to blindly display the contents of an error message?
  • I could send back a 400 Bad Request response, with a proprietary special header indicating that such-and-such header had the wrong code. This has the benefit that the client can actually process what the error was (as opposed to free text in the content). So does the 400 response then become a catch-all response, with the actual error in some proprietary header? Is this a good general pattern? But that almost suggests...
  • I could could send back some arbitrary 4XX response that has a proprietary meaning, such as 472 Bad Foo Header Value. Microsoft seems to have gone this route at times. The obvious problem is the possibility of clashes in a future version of HTTP (or with others who have done the same thing).

I suppose I'm leaning more toward 400 Bad Request with a special header indicating the error specialization. Any thoughts or experience with this use case?

1

There are 1 answers

5
Nils On BEST ANSWER

If the special header is incorrectly formatted then you could send a 400 Bad request Response indicating that the header is wrong.

However If the sole purpose of the header is authorization and you reject the header, because of invalid value, then I would opt for:

  1. 403 - Forbidden, if you want the connection to be refused
  2. 401 - Unauthorized, if the client should try to reauthenticate

In the Response phrase you can indicate the reason for refusing the connection.