alexeypro alexeypro - 11 months ago 66
Java Question

Best practices (examples?) on organizing versioned REST API code in Java/Spring project?

I am curios if anybody can point me to a good example/best practice of organizing REST API code with versioning (uri-based, means "/v1/zzz" and "/v2/xxx" or even better something relying on Accept header) -- in Java/Spring project? I am afraid I am making it too complicated in my project right now, so it'd be nice to learn from others.

Clarification: not sure if I should do it through filters, and then use some design pattern to change the behavior, but this will make my filter pretty complicated.. or may be I am not thinking about some trick with spring and DI, so I can make my code cleaner. the simplest approach is some strategy pattern in every method which will have different versioning, but it doesn't seem to be too clean neither :-(

ams ams
Answer Source

I highly recommend reading the book and blogs on Apigee I found that it gave me really practical advice for designing the urls and doing error handling. has a really great article on how to configure spring mvc to do generic error handling for restful applications.

As for filtering on accept headrs that is pretty easy to do since spring lets you narrow a handler method mapping based on the filter, as in the headers= in the request mapping below.

public ResponseEntity<String> narrowOnHeaders(
        @PathVariable("name")String name, 
        @PathVariable("email") String email, 
        @PathVariable("customerNumber") Integer customerNumber,
        @RequestHeader("Referer") String referer