stridecolossus
stridecolossus

Reputation: 1561

Augmenting Spring Rest API with common 'header'

I have a number of Spring REST end-points that are all required to return JSON with the following structure:

"code": 0,
"status": "SUCCESS",
"debug": {
    ...
},
"someData": {
    ...
}

The status, code and debug section are a common 'header' on every response but 'someData' is specific to each end-point, has a different name for each response and in a couple of cases consists of multiple elements at the same level in the response.

In particular the status and code are always the same for a successful response. (Note that there is also a global @ControllerAdvice for handling custom and un-caught exceptions that return a status/code/message error response).

Obviously we can simply create new POJOs for each controller that (say) extend some base-class containing the common stuff and adds the specifics letting Spring/Jackson do the rest (no pun intended).

But I was hoping there is some cunning way I can 'decorate' the specific responses with the generic code/status/debug bits. AOP seems over-kill, ditto custom Jackson converters.

Note that we cannot change the requirements (e.g. to use 'proper' HTTP response codes, headers, etc) as it's an existing and live API.

Upvotes: 1

Views: 456

Answers (2)

Graff Vynda-K
Graff Vynda-K

Reputation: 93

I also agree with jack's answer as being the "right way" to do this, however given your requirements you might take a look at using Spring's interceptor handlers:
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html

You could write a small handler that would override the postHandle() method and then you'd have access to the HttpServletResponse object. (and could - in theory - decorate it with those custom pieces of header info) I've done this in the past for intercepting requests, but never responses so I'm taking a bit of a stab here. (I would have posted this as a comment rather than an "answer" but I don't have enough rep points yet)

Whether this is any less-bad/less-overkill than using AOP I'm not sure. :)

Upvotes: 0

jack
jack

Reputation: 303

I'd recommend having a separate class for each response type you expect. If they all contain code/status/debug, then have a base class and set each response type to extend that base class.

Additionally, REST is set up to contain not only a response body but also response headers and response status codes (Link to glossary on w3.org), some of which are standard. There is also plenty of room for other custom codes. Instead of including code and status in your response body, why not set the code instead?

Upvotes: 3

Related Questions