Sub topic 2
Choosing a versioning strategy
This chapter helps you pick where a client states which API version it wants. It assumes you can write Spring MVC controllers with @RestController and @GetMapping, and that you know HTTP headers, query parameters and status codes. It also assumes you can read @Configuration classes. The mechanics of each option come in later chapters. Here the goal is a sound decision.
What a strategy decides
An API versioning strategy is the rule for how a client tells the server which version of an endpoint it wants. Spring Framework 7 reads that value with a version resolver. The resolver pulls a version string out of the request. Spring then matches it against the version attribute on your mappings.
Four places can carry the version:
- A request header, such as
X-API-Version: 2.0. - A path segment, such as
/v2/accounts/1. - A query parameter, such as
/accounts/1?version=2.0. - A parameter on the media type, such as
Accept: application/json;version=2.0.
The controller code looks almost the same in all four cases. The strategy changes how clients build requests, how caches behave, how you test, and how easy the API is to explore by hand. You usually make this choice once, so it is worth getting right.
Comparing the four options
| Strategy | Example | Visible in URL | Easy to try in a browser | Cache-friendly by default | Typical fit |
|---|---|---|---|---|---|
| Request header | `X-API-Version: 2.0` | No | No | No, needs `Vary` | Internal and service-to-service APIs |
| Path segment | `/v2/accounts/1` | Yes | Yes | Yes | Public APIs, simple client tooling |
| Query parameter | `?version=2.0` | Yes | Yes | Yes, if the cache keys on the query | Quick adoption, easy debugging |
| Media type parameter | `Accept: application/json;version=2.0` | No | No | No, needs `Vary: Accept` | Content negotiation purists |
Request header
The client sends a custom header. The URL names the resource and the header names the representation, so one URL keeps its meaning across versions. Links, bookmarks and stored identifiers stay valid when you release a new version.
The costs are practical. A browser address bar cannot send a custom header, so manual checks need curl or a REST client. A shared cache must be told that the response depends on the header, which means adding Vary: X-API-Version. A cache that ignores Vary could return a version 1 body to a version 2 client.
Path segment
The version is part of the URL. This is the easiest option to see, log, route and document. A gateway or load balancer can route /v2/* to a separate deployment without reading any header. Caches treat each version as a separate resource with no extra setup.
The drawback is that the same resource now has one URL per version. Clients that store links must rewrite them on migration. Purists say the version describes a representation, not a resource, so it does not belong in the URL. That is a style argument. In practice, path versioning is the most common choice for public APIs because it is so easy to use.
Query parameter
This keeps the base path stable and stays visible and easy to type. It works in a browser and is simple to add to an existing client. Two problems come up. Caches and proxies must treat the query string as part of the cache key, and some of them strip or normalize it. Also, the parameter mixes with real filter parameters, so a typo like ?versoin=2.0 silently falls through to the default version.
Media type parameter
The client puts the version in the Accept header, for example application/json;version=2.0. This fits HTTP content negotiation, because the version is a property of the representation the client asks for. It is the least convenient for clients. Many HTTP libraries and API gateways make custom Accept values awkward, and documentation tools often need extra configuration. It also needs Vary: Accept.
Matching the strategy to your situation
Ask these questions in order:
- Who calls the API? If you control every client, a header is simple and keeps URLs clean. If third parties call it, visibility counts for more.
- Does infrastructure need to see the version? Gateways, rate limiters and routers read paths easily. They read headers only if configured to.
- Do clients store or share links? If so, a version in the path breaks stored links when clients upgrade.
- How much do you rely on caching? Path and query versions work with plain URL caches. Header and media type versions need correct
Varyhandling. - How do people explore the API? If developers paste URLs into a browser, prefer path or query.
The diagram below puts these questions into a single decision path.
How the choice appears in Spring configuration
You register exactly one resolver through ApiVersionConfigurer in a WebMvcConfigurer. The resolver method is the only part that changes between strategies. The supported versions, the default and the version attributes on controllers stay the same.
For a header, this is the configuration from the earlier overview:
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");
}
}To switch to a query parameter, you replace one call. Nothing else in the class changes:
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.useQueryParam("version")
.addSupportedVersions("1.0", "1.1", "2.0")
.setDefaultVersion("1.0");
}
}The configurer offers matching methods for the other two strategies: usePathSegment for the path and useMediaTypeParameter for the Accept parameter. The path option needs a bit more care, because the version has to be part of the URL structure your mappings expect. The next chapters cover the exact setup.
Controllers do not mention the strategy. This mapping works the same under any resolver:
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");
}
}This separation makes a later change of strategy cheaper than it looks. You change the configuration, update clients and documentation, and leave the handler methods alone.
Edge cases and common errors
- One resolver only. Pick one source per application. Supporting both a header and a path segment means two resolvers, which Spring versioning does not give you. A client that sends the wrong one gets the default version, not an error.
- Silent fallback. If you set a default version, a client with a misspelled header name or parameter name is treated as having sent no version. Check this with a test that sends a wrong name and confirms what you want to happen.
- Missing
Vary. Header and media type strategies can serve the wrong cached body through a shared cache unless responses carryVaryfor the header you use. Check this on your gateway or CDN, not only in local runs. - Documentation drift. Header and media type versions are easy to leave out of OpenAPI documents and examples. Whichever strategy you choose, put a sample request in the docs.
- Mixing styles over time. Moving from a query parameter to a path segment later forces every client to change at once, unless you run both for a while. Decide early, and treat a change of strategy as a breaking change of its own.
Summary of the decision
- Choose a path segment for public APIs, gateway routing and easy exploration, and accept that URLs change between versions.
- Choose a header for internal APIs where stable URLs and a clean address space matter more than visibility.
- Choose a query parameter for a quick, browser-friendly option, and watch cache keys and typos.
- Choose a media type parameter when you want versioning inside HTTP content negotiation and your clients can handle custom
Acceptvalues.
Exercise
Your team runs a public API behind a gateway that routes traffic by URL prefix and caches responses by URL only. Which strategy fits best, and what would go wrong with a custom header strategy in this setup?
Show answer
A path segment fits best. The gateway can route /v2/* without reading headers, and a URL-keyed cache stores each version separately. With a custom header, the cache would key only on the URL, so it could return a version 1 body to a client that asked for version 2. Fixing this needs Vary: X-API-Version and a cache that honors it.
Exercise
You switch the configuration from useRequestHeader("X-API-Version") to useQueryParam("version"). Which parts of the application must change besides that one call?
Show answer
The controllers do not change, because the version attribute on the mappings is independent of the resolver. The clients must change to send ?version=... instead of the header, and the tests, documentation and any gateway or cache rules must be updated to match.