Using Custom Headers for Response Messages; Bad Practice?
I am working on a REST API using Java and the Spring Framework. Currently, I return a message from the server in a custom HTTP header called Server-Response
. This is used in both cases where errors occur and successful requests are completed. Is using a custom HTTP header for this purpose a bad practice?
Why did I do this?
List<Object>
, then I cannot return an additional string. Why not to do this?
@ExceptionHandler
annotation to allow exceptions to be handled differently, allowing for a String
response. Sample GET Request
I can get a list of locations from the following example URL: https://fakeurl.com/api/locations
Request Headers
Response Headers
Response Body
[
{"locId":1,"descr":"New York","activeStatus":"ACTIVE"},
{"locId":2,"descr":"Los Angelas","activeStatus":"ACTIVE"},
{"locId":3,"descr":"Canada","activeStatus":"ACTIVE"},
{"locId":4,"descr":"Mexico","activeStatus":"ACTIVE"},
{"locId":5,"descr":"Nebraska","activeStatus":"ACTIVE"},
{"locId":6,"descr":"Texas","activeStatus":"ACTIVE"},
{"locId":7,"descr":"Michigan","activeStatus":"ACTIVE"}
]
TL/DR: it depends on your actual usage.
It really depends on how you process the information that you pass in a custom header. It makes sense to use a custom header if you want to pass information at an enveloppe level. I mean, this information has nothing to do with the data that you want to retrieve, and as such should not be stored there, but is used by an encapsulating tool. A real world example would be a data server that could be accessed through different protocols, say HTTP and for example mail (replies with another mail) and a dedicated protocol. In that case the information on why or how the actual server could not be reached should be passed at an enveloppe level and a custom response header would be particurlarly adapted.
Another example would be when you use the same tool to access different information types. The payload should only contain the actual information, that would be transparently passed to a caller, and the error conditions could be passed in a response headers and would be processed by the exchange tool.
The only rule you should obey is that a custom header should begin by X-
.