Sub topic 3
Enabling versioning with ApiVersionConfigurer
This chapter assumes you can write Spring MVC controllers with @RestController and @GetMapping, and that you have used @Configuration classes in Spring Boot. You should also know what an HTTP header is. Earlier chapters covered why and when to version an API and how to choose a strategy. Here you turn versioning on and read the configuration closely.
What the configurer does
Spring Framework 7, which Spring Boot 4 builds on, has built-in API versioning. It is off until you configure it. Without configuration, the version attribute on @GetMapping and similar annotations has no version source to compare against.
ApiVersionConfigurer is the object you use to switch it on. Spring passes it to your WebMvcConfigurer through the configureApiVersioning callback. In WebFlux the same idea exists on WebFluxConfigurer.
Configuration answers four questions:
- Where does the version come from? A header, a path segment, a query parameter, or a media type parameter.
- Which versions does the application support?
- What happens when a request has no version?
- How is the raw text turned into a comparable version?
This chapter covers the first and second questions and shows the callback that holds all four. Later chapters go deeper on parsing, defaults, and errors.
A minimal configuration
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 ApiVersionConfig implements WebMvcConfigurer {
@Override
public void configureApiVersioning(ApiVersionConfigurer configurer) {
configurer.useRequestHeader("X-API-Version")
.addSupportedVersions("1.0", "1.1", "2.0")
.setDefaultVersion("1.0");
}
}Each call does one job:
useRequestHeader("X-API-Version")registers a version resolver that reads the header with that name.addSupportedVersions("1.0", "1.1", "2.0")lists the versions the application accepts.setDefaultVersion("1.0")names the version to use when a request has none.
The configurer methods return the configurer, so the calls chain. The class is an ordinary @Configuration bean. Spring MVC finds the WebMvcConfigurer and calls the method while it builds its infrastructure. You do not register anything else.
How a request flows through versioning
When a request arrives, Spring MVC runs the resolver first. It parses the result into a version object and checks it against the supported versions. Only then does it compare it with the version attributes on candidate handler methods.
Resolution and validation happen once per request, before handler selection. If the check fails, no controller method runs.
Choosing where the version lives
The configurer has one method for each common strategy. You pick exactly one source of the version for the application.
| Strategy | Configurer method | Example request |
|---|---|---|
| Request header | `useRequestHeader("X-API-Version")` | `GET /accounts/1` with header `X-API-Version: 2.0` |
| Query parameter | `useQueryParam("version")` | `GET /accounts/1?version=2.0` |
| Path segment | `usePathSegment(index)` | `GET /v2.0/accounts/1` |
| Media type parameter | `useMediaTypeParameter(mediaType, "version")` | `Accept: application/json;version=2.0` |
Some details matter in practice:
- Header and query parameter are the simplest. They need nothing in your mappings beyond the
versionattribute, and the path stays the same across versions. - Path segment takes the zero-based index of the segment that holds the version. The version is part of the URL, so your mapping paths must contain a matching variable such as
/{version}. A shared prefix on the controller is the usual place for it. This is the strategy where the URL changes between versions, which some teams prefer for caching and for readability in logs. - Media type parameter reads a parameter from a media type, usually
Accept. You pass the media type to inspect, for exampleMediaType.APPLICATION_JSON, and the parameter name.
If none of these fits, useVersionResolver(...) accepts your own ApiVersionResolver. A resolver is a function from the request to the raw version text, or null when there is none. Use it for sources such as a claim in an authentication token or a lookup on the client identity. The built-in methods cover most services, so reach for a custom resolver only when they do not.
Supported versions
addSupportedVersions declares the versions the application accepts. The call is additive. Call it more than once and the lists combine.
configurer.useRequestHeader("X-API-Version")
.addSupportedVersions("1.0", "1.1")
.addSupportedVersions("2.0");This is the same as passing all three values in one call.
Spring also collects versions from the version attributes it finds in your mappings. By default these detected versions count as supported. That is convenient, but it means a typo in a mapping can quietly add a version nobody meant to publish. An explicit list gives you one place to review what the API promises. If you want that list to be the only source of truth, turn detection off with detectSupportedVersions(false).
configurer.useRequestHeader("X-API-Version")
.addSupportedVersions("1.0", "1.1", "2.0")
.detectSupportedVersions(false);With detection off, a mapping that declares a version missing from the list never receives requests for it, because the request is rejected during validation.
The version parser
The raw text from the resolver is converted by an ApiVersionParser. The default parser reads dotted numbers such as 1, 1.1, or 2.0. Missing minor and patch parts are treated as zero, so 2 and 2.0 count as the same version. Ordering is numeric, so 1.10 is later than 1.9. You do not need to configure this for the examples in this tutorial. Replace it with setVersionParser(...) only when your clients send a different format, such as a date-based version.
Using the version in a controller
Once the configurer is in place, two methods can share one path and differ by version.
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("/accounts")
public class AccountController {
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");
}
}A request with X-API-Version: 1.0 reaches getV1. A request with 2.0 reaches getV2. A request with no header uses the default of 1.0 and also reaches getV1. The trailing + in "2.0+" makes a baseline version that matches 2.0 and later supported versions. A later chapter covers that.
Without the configurer, this controller would fail to start or would not match as intended, because there would be no version source to compare against.
Common mistakes
- Configuring a resolver but forgetting supported versions. Requests then rely entirely on detection from mappings. This works until a mapping is renamed or removed.
- Defaulting to the newest version. A default is what clients without a version receive. If you set it to the latest version, your next breaking change breaks every client that never sent a header. Default to the oldest stable version, or require the version.
- Version values that do not parse. A value such as
v2is not a dotted number for the default parser. Keep the declared versions and the client values in a numeric format. - Mixing strategies. Only one resolver strategy drives versioning. Do not expect a header to work for some clients and a query parameter for others.
- Putting configuration in the wrong interface. In a reactive application, implement the WebFlux configurer and its own
ApiVersionConfigurer. The servlet class does not apply there.
Checking your setup
To check that versioning is active, call the endpoint with and without the header.
curl -H "X-API-Version: 2.0" http://localhost:8080/accounts/1
curl http://localhost:8080/accounts/1The first call should return the split name fields. The second should return the single name field from the default version. If both return the same body, check that your configuration class is in a scanned package and that the header name matches exactly.
Exercise
Your service uses useRequestHeader("X-API-Version"), addSupportedVersions("1.0", "2.0"), detectSupportedVersions(false), and setDefaultVersion("1.0"). A developer adds a controller method with version = "3.0" and deploys. A client sends X-API-Version: 3.0. What happens, and what is the smallest change that makes the version available?
Show answer
The request is rejected during validation, because 3.0 is not in the explicit supported list and detection from mappings is off, so no controller method runs. The smallest change is to add "3.0" to addSupportedVersions, for example addSupportedVersions("1.0", "2.0", "3.0"). That makes it a deliberate decision to publish the version.
Exercise
Why can calling addSupportedVersions twice be safe, and why is defaulting to the latest version risky?
Show answer
The method is additive, so a second call adds to the list. Defaulting to the latest version is risky because clients that send no version always receive the newest behavior, so the next breaking change breaks them without any change on their side.