4

We are considering using a header field to specify the REST API version in our spring boot application.

How can we tell spring boot to redirect calls depending on a header value?

I am dreaming about something like this:

@Path("/my/rest/path")
@HeaderMapping(headerName="ApiVersion", headerValue="V1")
public class V1Controller {

    @GetMapping
    public String myMethod() {
    }
}

== and ==

@Path("/my/rest/path")
@HeaderMapping(headerName="ApiVersion", headerValue="V2")
public class V2Controller {

    @GetMapping
    public String myMethod() {
    }
}

for HTTP requests like these:

GET /my/rest/path HTTP/1.1
Accept: application/json
ApiVersion: V1

== or ==

GET /my/rest/path HTTP/1.1
Accept: application/json
ApiVersion: V2
slartidan
  • 20,403
  • 15
  • 83
  • 131

2 Answers2

4

This seems to work:

@Path("/my/rest/path")
public class V1Controller {

    @GetMapping(headers = "ApiVersion=V1")
    public String myMethod() {
    }
}

== and ==

@Path("/my/rest/path")
public class V2Controller {

    @GetMapping(headers = "ApiVersion=V2")
    public String myMethod() {
    }
}

PS: Not yet tested, but seen in a Spring boot tutorial.

slartidan
  • 20,403
  • 15
  • 83
  • 131
1

Yeap exactly: e.g

PUT method #1
@RequestMapping(method=RequestMethod.PUT, value="/foo", 
headers="returnType=Foo")
public @ResponseBody Foo updateFoo(@RequestBody Foo foo) {
fooService.update(foo);
}

//PUT method #2
@RequestMapping(method=RequestMethod.PUT, value="/foo", 
headers="returnType=FooExtra")
public @ResponseBody FooExtra updateFoo(@RequestBody FooExtra fooExtra) {
fooService.update(fooExtra);
}

Here you get documentation : adding custom header