Spring MVC Versioning

I have a spring boot application that has a spring MVC controller. I am trying to execute my rest api version using the Accept header.

Below is what my controller looks like:

RestController @RequestMapping(value = "/private/") public class AppleController { private final AppleService appleService; public AppleController(AppleService appleService) { this.appleService = appleService; } @GetMapping(value = "apples/{id}", produces = "application/json; v=1.0", headers = "Accept=application/json; v=1.0") public ResponseEntity getByappleId(@PathVariable("id") Long appleId) { System.out.println("version1"); GetByappleIdResponse response = appleService.findByappleId(appleId); return new ResponseEntity<>(response, HttpStatus.OK); } @GetMapping(value = "apples/{id}", produces = "application/json; v=2.0", headers = "Accept=application/json; v=2.0") public ResponseEntity getByappleId2(@PathVariable("id") Long appleId) { System.out.println("version2"); GetByappleIdResponse response = appleService.findByappleId2(appleId); return new ResponseEntity<>(response, HttpStatus.OK); } 

Regardless of the version that I pass in the Accept header when calling the API, the getByappleId method is always called, so only version 1 response is returned.

Is there something wrong with my controller?

+7
spring-boot spring-mvc spring-restcontroller
source share
2 answers

As described in this answer: fooobar.com/questions/845924 / ... (and mentioned in the comments) Spring does not support routing using such headers.

If you want to support routing through the version header, I would recommend a custom routing condition and annotation - of course, if you create a large API, this will reduce the amount of code and a more elegant solution.

You would define some annotation like @ApiVersion(1) , which you can add to any method that is also a query display, and then add a custom routing condition and behave correctly.

I described the use of custom routing conditions and annotations (based on subdomains, but instead they could be easily switched to check headers): http://automateddeveloper.blogspot.co.uk/2014/12/spring-mvc-custom-routing- conditions.html

+2
source share

There are many options for implementing REST API management:

  • comments suggested in the approach for manually routing your request;
  • make the version part of your Accept header value, fe:

    (headers = "Accept=application/vnd.name.v1+json")

    (headers = "Accept=application/vnd.name.v2+json")

  • creating a version as part of your display:

    @GetMapping("apples/v1/{id})"

    @GetMapping("apples/v2/{id})

So, you need to decide which way to go. Some useful links:

+4
source share

All Articles