Sub topic 4
Reading the version from a header, path, query parameter or media type
This chapter covers how Spring MVC finds the requested version in an incoming request. It assumes you can write @RestController classes, know what WebMvcConfigurer is, and can read HTTP headers and query strings. You should also have seen ApiVersionConfigurer and the version attribute on @GetMapping, which earlier chapters introduced.
What a version resolver does
A version resolver is the component that extracts a raw version string from a request. It does nothing else. The steps that follow are separate:
- The resolver reads a string such as
"2.0"from the request, or returns nothing. - The version parser turns the string into a comparable
Comparableversion object. - Spring checks the parsed version against the supported versions.
- Spring picks the handler method whose
versionattribute matches.
If the resolver finds nothing, Spring applies the default or required rules covered in a later chapter. Everything here concerns step 1.
The four built-in sources
ApiVersionConfigurer has one method for each built-in source. You pick the source in a WebMvcConfigurer.
| Strategy | Configurer method | Example request |
|---|---|---|
| Request header | `useRequestHeader("X-API-Version")` | `X-API-Version: 2.0` |
| Query parameter | `useQueryParam("version")` | `/accounts/1?version=2.0` |
| Path segment | `usePathSegment(1)` | `/api/2.0/accounts/1` |
| Media type parameter | `useMediaTypeParameter(MediaType, "version")` | `Accept: application/json;version=2.0` |
Configure one source per application. A configurer holds a single resolver, so a second use... call replaces the first and does not add a fallback. If you need to accept two sources, write a custom resolver (see below).
Request header
A header keeps the URL stable and puts the version in request metadata. This is the strategy the Topic Spine's examples use.
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ApiVersionConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class HeaderVersionConfig implements WebMvcConfigurer {
@Override
public void configureApiVersioning(ApiVersionConfigurer configurer) {
configurer.useRequestHeader("X-API-Version")
.addSupportedVersions("1.0", "2.0");
}
}A client sends the header like this:
curl -H "X-API-Version: 2.0" http://localhost:8080/accounts/1Header names are case-insensitive in HTTP, so x-api-version works too. The trade-off is visibility. You cannot open a header-versioned endpoint in a browser address bar or paste it into a chat message. Caches must also include the header in their cache key. Add Vary: X-API-Version to responses if a shared cache sits in front of your service.
Query parameter
A query parameter is easy to try by hand and easy to put in a link.
@Override
public void configureApiVersioning(ApiVersionConfigurer configurer) {
configurer.useQueryParam("version")
.addSupportedVersions("1.0", "2.0");
}curl "http://localhost:8080/accounts/1?version=2.0"The query string is part of the cache key in most caches, so caching behaves correctly without extra work. The parameter name is also visible in logs and in browser history. Do not use a name that your handlers already bind with @RequestParam, because the same value would serve two purposes.
Path segment
Path versioning puts the version in the URL. You tell Spring which segment holds it by its zero-based index.
@Override
public void configureApiVersioning(ApiVersionConfigurer configurer) {
configurer.usePathSegment(1)
.addSupportedVersions("1.0", "2.0");
}With index 1, the request /api/2.0/accounts/1 yields "2.0". Segment 0 is api. Counting starts after the context path, if you have one.
The version segment stays in the URL, so each mapping must contain a placeholder at that position. You still use the version attribute to select the handler:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/{version}/accounts")
public class PathAccountController {
record AccountV1(long id, String name) {}
record AccountV2(long id, String firstName, String lastName) {}
@GetMapping(path = "/{id}", version = "1.0")
public AccountV1 getV1(@PathVariable long id) {
return new AccountV1(id, "Ada Lovelace");
}
@GetMapping(path = "/{id}", version = "2.0+")
public AccountV2 getV2(@PathVariable long id) {
return new AccountV2(id, "Ada", "Lovelace");
}
}The placeholder name (version here) is free to choose. You normally do not bind it to a method parameter, because the resolver has already consumed it.
The default parser expects dotted numeric versions such as 1, 1.1 or 2.0. A prefix like v2 needs a custom parser, which a later chapter covers. For that reason the examples use /api/2.0/... and not /api/v2/....
Path versioning has the strongest visibility and caches well. It also changes the URL of every resource when the version changes, which affects bookmarks, links stored in data and HATEOAS-style responses.
Media type parameter
Here the version travels as a parameter on a media type in the Accept header. This follows the HTTP content negotiation model, where the client asks for a representation of the resource.
import org.springframework.http.MediaType;
@Override
public void configureApiVersioning(ApiVersionConfigurer configurer) {
configurer.useMediaTypeParameter(MediaType.APPLICATION_JSON, "version")
.addSupportedVersions("1.0", "2.0");
}The first argument names the media type whose parameter carries the version. The second names the parameter.
curl -H "Accept: application/json;version=2.0" http://localhost:8080/accounts/1Requests that send a different media type, or no parameter, produce no version. Browsers and many tools send Accept: */* by default, so those clients get the default version, if you set one. This option is the most protocol-correct and the least convenient. It is also the easiest to forget when writing client code.
Writing a custom resolver
When none of the built-in sources fits, implement ApiVersionResolver and register it with useVersionResolver. The resolver receives the request and returns the version string, or null when the request carries none. This lambda accepts a version from either a header or a query parameter:
@Override
public void configureApiVersioning(ApiVersionConfigurer configurer) {
configurer.useVersionResolver(request -> {
String fromHeader = request.getHeader("X-API-Version");
return fromHeader != null ? fromHeader : request.getParameter("version");
}).addSupportedVersions("1.0", "2.0");
}Keep a custom resolver cheap and free of side effects. It runs on every request that reaches a versioned mapping. Return null for "no version", and do not throw an exception. Spring then handles the missing version consistently with the rest of your configuration.
Choosing a source
- Use a header when you control the clients and want clean URLs.
- Use a query parameter for public APIs where people try requests by hand.
- Use a path segment when the version must be obvious in logs, gateways and documentation, and when routing at a reverse proxy by path is needed.
- Use a media type parameter when you follow strict content negotiation rules and your clients can set
Acceptprecisely.
Verifying a resolver with a test
A test that sends the version through the configured source proves the resolver is wired correctly. This one assumes the query parameter configuration above and an AccountController with 1.0 and 2.0+ handlers.
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
class QueryParamVersioningTests {
@Autowired
MockMvc mockMvc;
@Test
void queryParameterSelectsVersion() throws Exception {
mockMvc.perform(get("/accounts/1").param("version", "2.0"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.firstName").value("Ada"));
}
}Common errors
- Version sent through the wrong channel. The client sets a header while the server reads a query parameter. The resolver finds nothing, so you see the default version or a missing-version error.
- Wrong path index. The segment read is not the version, so the value fails parsing or the supported-versions check.
- Missing placeholder in a path-versioned mapping. The URL contains the version segment, but no mapping pattern matches it, so you get a 404.
- Media type mismatch. The
Acceptheader names a type other than the one given touseMediaTypeParameter, so no version is read. - Mixing sources. Calling two
use...methods and expecting both to work. Only the last one applies.
Exercise
A service is configured with configurer.usePathSegment(1).addSupportedVersions("1.0", "2.0"). A client calls /accounts/2.0/1. Why does version resolution fail, and what request path would work with this configuration?
Show answer
Index 1 is the second segment, which here is 2.0's neighbour: segment 0 is accounts and segment 1 is 2.0, so the resolver reads 2.0 correctly, but the mapping still needs a placeholder at that position, such as /accounts/{version}/{id}. If the mapping is /api/{version}/accounts/{id}, the request does not match it, so the result is a 404 and the resolver never matters. The matching path is /api/2.0/accounts/1 with the index changed to 1 for the api prefix, or /accounts/2.0/1 with a mapping of /accounts/{version}/{id}. The index and the mapping pattern must agree on where the version sits.
Exercise
Name two reasons a team might prefer a request header over a query parameter, and one reason they might choose the query parameter instead.
Show answer
A header keeps URLs identical across versions, and it keeps the version out of logs and browser history that record URLs. The query parameter is easier to try by hand in a browser or link, and shared caches already include it in the cache key without a Vary header.