PAA
PAA

Reputation: 12063

Spring Boot Rest - How to accept multiple headers

I am using Spring Boot V2.2.2.RELEASE and doing API versioning using custom headers. I developed small endpoint like this:

@GetMapping(value = "/student/header", headers = {"X-API-VERSION=2", "X-API-VERSION=1"})
public StudentV1 headerV2() {
    return new StudentV1("Bob Charlie");
} 

When I hit curl -X GET http://localhost:8080/student/header -H 'x-api-version: 1', I get the error.

{
    "timestamp": "2020-01-13T09:20:20.087+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/student/header"
}

If I used headers = {"X-API-VERSION=2"}, then it works, but if I used headers = {"X-API-VERSION=2", "X-API-VERSION=1"}, then things stop working.

@GetMapping(value = "/student/header", headers = {"X-API-VERSION=2"})
public StudentV1 headerV2() {
  return new StudentV1("Bob Charlie");
}

Upvotes: 2

Views: 4779

Answers (1)

Marc Stroebel
Marc Stroebel

Reputation: 2357

using headers = {"X-API-VERSION=2", "X-API-VERSION=1"} both headers must be present.

Try using one mapping per header and then forward to your service impl.

@GetMapping(value = "/student/header", headers = {"X-API-VERSION=1"})
public StudentV1 headerV1() {
    return serviceImpl.headerV1();
}

@GetMapping(value = "/student/header", headers = {"X-API-VERSION=2"})
public StudentV1 headerV2() {
    return serviceImpl.headerV2();
}

Upvotes: 2

Related Questions