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?
- Cases exist where I need the body for an object but require an additional string response.
- Java is strictly typed; if I return a
List<Object>
, then I cannot return an additional string. - Messages from the server must be more specific than what is provided by a global exception handler.
Why not to do this?
- Spring provides a
@ExceptionHandler
annotation to allow exceptions to be handled differently, allowing for aString
response. - Maybe headers should not contain important information such as error messages.
Sample GET Request
I can get a list of locations from the following example URL: https://fakeurl.com/api/locations
Request Headers
- Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
- Accept-Encoding:gzip, deflate, sdch Accept-Language:en-US,en;q=0.8
- Cache-Control:no-cache Connection:keep-alive
- Upgrade-Insecure-Requests:1
- User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36
- Status Code:200 OK
Response Headers
- Content-Type:application/json;charset=UTF-8
- Date:Wed, 11 May 2016 15:41:03 GMT
- Expires:Wed, 31 Dec 1969 19:00:00 EST Expires:-1
- Server:Apache-Coyote/1.1
- Server Response:Successfully retrieved all locations!
- Transfer-Encoding:chunked
- X-Powered-By:Servlet 2.5; JBoss-5.0/JBossWeb-2.1
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"}
]
Response
object that contains all the fileds you like, it can act like a container for everything like stackoverflow.com/questions/12806386/… – zapl