Spring API versioning: several versions of one endpoint
Spring Framework 7 made API versioning part of request mapping: a version attribute on the mapping and one setting that says where clients put the version. This page explains how versions are resolved, parsed and validated, then runs header, query, path and media type versioning, baseline versions, deprecation headers and a versioned RestClient.
Contents
Why API versioning, and what Spring Framework 7 added
A public API cannot change its responses freely. Mobile apps stay installed for years, and partners deploy on their own schedule, so renaming a field or changing its type breaks clients you do not control. API versioning lets the old and the new shape live side by side: each client says which version it was written for, and the server answers in that version until the old one is retired.
Until Spring Framework 7.0, Spring had no built-in support for this. Applications put /v1/version@GetMappingspring.mvc.apiversion.*
The support has four parts, all configurable:
- Resolver: reads the version from the request: a header, a query parameter, a path segment or a media type parameter.
- Parser: turns the text into a comparable version. The default
reads major, minor and patch numbers, and sets missing parts to 0, soSemanticApiVersionParser means 2.0.0.2 - Validation: rejects versions that are not supported, and missing versions when a version is required.
- Deprecation handler: adds standard headers that tell clients a version is going away.
| Strategy | Example request | Spring Boot property | Best for |
|---|---|---|---|
| Request header | API-Version: 2.0 | spring.mvc.apiversion.use.header | APIs used by programs; keeps URLs stable |
| Query parameter | /price?version=2 | spring.mvc.apiversion.use.query-parameter | Easy testing in a browser |
| Path segment | /api/v2/price | spring.mvc.apiversion.use.path-segment | Public APIs where the version should be visible and cacheable |
| Media type parameter | Accept: application/json;v=2 | spring.mvc.apiversion.use.media-type-parameter | APIs that already use content negotiation |
The programs use Spring Boot 4.1 with Spring Framework 7.0 and spring-boot-starter-webmvc
Versions in a header
An order API that changed its totalAPI-Version
package demo.header;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class HeaderVersions {
public record OrderV1(long id, String customer, String total) {}
public record Money(String amount, String currency) {}
public record OrderV2(long id, String customer, Money total) {}
@RestController
static class OrderController {
@GetMapping(path = "/orders/{id}", version = "1.0+") // 1.0 and later
public OrderV1 v1(@PathVariable long id) {
return new OrderV1(id, "Ana", "12.50 EUR");
}
@GetMapping(path = "/orders/{id}", version = "2.0+") // 2.0 and later
public OrderV2 v2(@PathVariable long id) {
return new OrderV2(id, "Ana", new Money("12.50", "EUR"));
}
@GetMapping(path = "/customers", version = "1.2") // exactly 1.2
public String customers() {
return "[\"Ana\",\"Ben\"]";
}
}
static HttpClient http = HttpClient.newHttpClient();
static String base;
static void get(String path, String version) throws Exception {
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + path));
if (version != null) {
request.header("API-Version", version);
}
HttpResponse<String> r = http.send(request.build(), BodyHandlers.ofString());
System.out.printf("GET %-10s API-Version: %-5s -> %d %s%n",
path, version == null ? "-" : version, r.statusCode(), r.body());
}
public static void main(String[] args) throws Exception {
try (var context = new SpringApplicationBuilder(HeaderVersions.class)
.properties("server.port=0", "spring.main.banner-mode=off",
"logging.level.root=OFF",
"spring.mvc.problemdetails.enabled=true",
"spring.mvc.apiversion.use.header=API-Version",
"spring.mvc.apiversion.supported=1.0,1.1,1.2,2.0",
"spring.mvc.apiversion.default=1.0")
.run(args)) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
base = "http://localhost:" + port;
get("/orders/7", "1.0");
get("/orders/7", "1.1");
get("/orders/7", "2.0");
get("/orders/7", "2");
get("/orders/7", null);
get("/orders/7", "3.0");
get("/orders/7", "v-two");
get("/customers", "1.2");
get("/customers", "2.0");
}
}
}
GET /orders/7 API-Version: 1.0 -> 200 {"id":7,"customer":"Ana","total":"12.50 EUR"}
GET /orders/7 API-Version: 1.1 -> 200 {"id":7,"customer":"Ana","total":"12.50 EUR"}
GET /orders/7 API-Version: 2.0 -> 200 {"id":7,"customer":"Ana","total":{"amount":"12.50","currency":"EUR"}}
GET /orders/7 API-Version: 2 -> 200 {"id":7,"customer":"Ana","total":{"amount":"12.50","currency":"EUR"}}
GET /orders/7 API-Version: - -> 200 {"id":7,"customer":"Ana","total":"12.50 EUR"}
GET /orders/7 API-Version: 3.0 -> 400 {"detail":"Invalid API version: '3.0.0'.","instance":"/orders/7","status":400,"title":"Bad Request"}
GET /orders/7 API-Version: v-two -> 400 {"detail":"Invalid API version: 'v-two'.","instance":"/orders/7","status":400,"title":"Bad Request"}
GET /customers API-Version: 1.2 -> 200 ["Ana","Ben"]
GET /customers API-Version: 2.0 -> 400 {"detail":"Invalid API version: '2.0.0'.","instance":"/customers","status":400,"title":"Bad Request"}
is a baseline: the method serves 1.0 and every later version, until a newer mapping takes over. So 1.0 and 1.1 both got the v1 shape, withversion = "1.0+" ."total":"12.50 EUR"- For 2.0, both methods match, and Spring chose the one with the highest baseline that is not above the request, the
method. The v2 shape has2.0+ as an object.total without a minor version was parsed as 2.0.0 and treated exactly like2 .2.0- With no header,
applied and the client got v1. Without a default, a missing version is an error, as the deprecation example below shows.spring.mvc.apiversion.default=1.0 - 3.0 is not in the supported list, so Spring answered 400 with
, before choosing a method.Invalid API version: '3.0.0'. could not be parsed and got the same 400.v-two withoutversion = "1.2" is a fixed version. It answered 1.2 but not 2.0, even though 2.0 is supported. Fixed versions suit endpoints that exist in one version only; baselines avoid copying every unchanged method into each new version.+
Baselines are what make versioning manageable. When version 2.0 changes only the order endpoint, only that method needs a 2.0+1.0+1.1spring.mvc.apiversion.supportedInvalid API version: '1.1.0'.
Query parameters, path segments and media types
The controller code is the same for every strategy; only the configuration changes. The program runs a small price endpoint three times, once for each of the other strategies:
package demo.strategies;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class VersionStrategies {
@RestController
@ConditionalOnProperty(name = "demo.version-in-path", havingValue = "false")
static class PriceController {
@GetMapping(path = "/price", version = "1")
public String v1() {
return "v1: 12.50";
}
@GetMapping(path = "/price", version = "2")
public String v2() {
return "v2: 12.50 EUR";
}
}
@RestController
@ConditionalOnProperty(name = "demo.version-in-path", havingValue = "true")
static class PathPriceController {
@GetMapping(path = "/api/{version}/price", version = "1")
public String v1() {
return "v1: 12.50";
}
@GetMapping(path = "/api/{version}/price", version = "2")
public String v2() {
return "v2: 12.50 EUR";
}
}
static void run(String strategy, String... requests) throws Exception {
System.out.println("=== " + strategy);
boolean inPath = strategy.contains("path-segment");
try (var context = new SpringApplicationBuilder(VersionStrategies.class)
.properties("server.port=0", "spring.main.banner-mode=off",
"logging.level.root=OFF", strategy,
"demo.version-in-path=" + inPath)
.run()) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
HttpClient http = HttpClient.newHttpClient();
for (int i = 0; i < requests.length; i += 2) {
HttpRequest.Builder request = HttpRequest.newBuilder(
URI.create("http://localhost:" + port + requests[i]));
if (requests[i + 1] != null) {
request.header("Accept", requests[i + 1]);
}
HttpResponse<String> r = http.send(request.build(), BodyHandlers.ofString());
System.out.println("GET " + requests[i]
+ (requests[i + 1] == null ? "" : " Accept: " + requests[i + 1])
+ " -> " + r.statusCode() + " " + r.body());
}
}
}
public static void main(String[] args) throws Exception {
run("spring.mvc.apiversion.use.query-parameter=version",
"/price?version=1", null, "/price?version=2", null);
run("spring.mvc.apiversion.use.path-segment=1",
"/api/v1/price", null, "/api/2/price", null);
run("spring.mvc.apiversion.use.media-type-parameter[application/json]=v",
"/price", "application/json;v=1", "/price", "application/json;v=2");
}
}
=== spring.mvc.apiversion.use.query-parameter=version
GET /price?version=1 -> 200 v1: 12.50
GET /price?version=2 -> 200 v2: 12.50 EUR
=== spring.mvc.apiversion.use.path-segment=1
GET /api/v1/price -> 200 v1: 12.50
GET /api/2/price -> 200 v2: 12.50 EUR
=== spring.mvc.apiversion.use.media-type-parameter[application/json]=v
GET /price Accept: application/json;v=1 -> 200 v1: 12.50
GET /price Accept: application/json;v=2 -> 200 v2: 12.50 EUR
- Query parameter:
and?version=1 chose the two methods. The parameter is consumed by versioning and does not need a?version=2 .@RequestParam - Path segment:
reads the second path segment, counting from 0. The mappings must contain a placeholder in that position, hereuse.path-segment=1 . Both/api/{version}/price andv1 worked, because the parser ignores a leading letter2 .v - Media type parameter:
in theapplication/json;v=1 header chose v1. The property is a map from media type to parameter name, written asAccept .use.media-type-parameter[application/json]=v
The path strategy has one difference that matters: every request to the application must then have a version in that position, or it fails with InvalidApiVersionExceptionPredicate<RequestPath>usePathSegment(index, predicate)
Deprecating and retiring a version
Retiring a version takes months, and clients need a warning they can detect automatically. This program configures versioning in Java instead of properties, requires a version on every request, and marks 1.0 as deprecated with a sunset date:
package demo.deprecation;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.accept.StandardApiVersionDeprecationHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.ApiVersionConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SpringBootApplication
public class DeprecatedVersions implements WebMvcConfigurer {
@Override
public void configureApiVersioning(ApiVersionConfigurer configurer) {
StandardApiVersionDeprecationHandler deprecation =
new StandardApiVersionDeprecationHandler();
deprecation.configureVersion("1.0")
.setDeprecationDate(ZonedDateTime.of(2026, 6, 1, 0, 0, 0, 0, ZoneOffset.UTC))
.setSunsetDate(ZonedDateTime.of(2027, 1, 31, 0, 0, 0, 0, ZoneOffset.UTC))
.setSunsetLink(URI.create("https://example.com/docs/migrate-to-v2"));
configurer.useRequestHeader("API-Version")
.setVersionRequired(true)
.setDeprecationHandler(deprecation);
}
@RestController
static class InvoiceController {
@GetMapping(path = "/invoices", version = "1.0")
public String v1() {
return "invoices, v1 format";
}
@GetMapping(path = "/invoices", version = "2.0")
public String v2() {
return "invoices, v2 format";
}
}
public static void main(String[] args) throws Exception {
try (var context = new SpringApplicationBuilder(DeprecatedVersions.class)
.properties("server.port=0", "spring.main.banner-mode=off",
"logging.level.root=OFF",
"spring.mvc.problemdetails.enabled=true")
.run(args)) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
HttpClient http = HttpClient.newHttpClient();
for (String version : new String[] {"1.0", "2.0", null, "1.5"}) {
HttpRequest.Builder request = HttpRequest.newBuilder(
URI.create("http://localhost:" + port + "/invoices"));
if (version != null) {
request.header("API-Version", version);
}
HttpResponse<String> r = http.send(request.build(), BodyHandlers.ofString());
System.out.println("GET /invoices API-Version: "
+ (version == null ? "-" : version) + " -> " + r.statusCode());
System.out.println(" " + r.body());
for (String h : new String[] {"Deprecation", "Sunset", "Link"}) {
r.headers().firstValue(h)
.ifPresent(v -> System.out.println(" " + h + ": " + v));
}
}
}
}
}
GET /invoices API-Version: 1.0 -> 200
invoices, v1 format
Deprecation: @1780272000
Sunset: Sun, 31 Jan 2027 00:00:00 GMT
Link: <https://example.com/docs/migrate-to-v2>; rel="sunset"; type="text/html"
GET /invoices API-Version: 2.0 -> 200
invoices, v2 format
GET /invoices API-Version: - -> 400
{"detail":"API version is required.","instance":"/invoices","status":400,"title":"Bad Request"}
GET /invoices API-Version: 1.5 -> 400
{"detail":"Invalid API version: '1.5.0'.","instance":"/invoices","status":400,"title":"Bad Request"}
- The 1.0 response carried three headers.
is the deprecation date, 1 June 2026, as seconds since 1970, in the format of RFC 9745.Deprecation: @1780272000 is the date the version will stop working, as an HTTP date, from RFC 8594.Sunset withLink points to the migration guide.rel="sunset" - The 2.0 response carried none of them.
- Without a header, the request failed with 400 and
, fromAPI version is required. . A version is required by default whenever versioning is on and no default is set;MissingApiVersionException only makes that explicit.setVersionRequired(true) - 1.5 got 400 even though it lies between two mapped versions. No supported list was configured, so Spring detected the supported versions from the mappings, 1.0 and 2.0, and nothing else.
Client libraries and API gateways can log or alert on the DeprecationconfigureApiVersioningspring.mvc.apiversion.*ApiVersionConfigurer
Sending the version from a client
Clients must send the version on every request, and Spring's own HTTP clients can do it for you. RestClientApiVersionInserter
package demo.client;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.ApiVersionInserter;
import org.springframework.web.client.RestClient;
@SpringBootApplication
public class VersionedClient {
@RestController
static class StockController {
@GetMapping(path = "/stock", version = "1.0")
public String v1() {
return "stock v1";
}
@GetMapping(path = "/stock", version = "2.0")
public String v2() {
return "stock v2";
}
}
public static void main(String[] args) {
try (var context = new SpringApplicationBuilder(VersionedClient.class)
.properties("server.port=0", "spring.main.banner-mode=off",
"logging.level.root=WARN",
"spring.mvc.apiversion.use.header=API-Version")
.run(args)) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
// Shows the request line and version header the client actually sends
ClientHttpRequestInterceptor show = (request, body, execution) -> {
System.out.println(" sends " + request.getMethod() + " "
+ request.getURI().getRawPath()
+ " API-Version: " + request.getHeaders().getFirst("API-Version"));
return execution.execute(request, body);
};
RestClient client = RestClient.builder()
.baseUrl("http://localhost:" + port)
.apiVersionInserter(ApiVersionInserter.useHeader("API-Version"))
.defaultApiVersion("1.0")
.requestInterceptor(show)
.build();
System.out.println("default version:");
System.out.println(" got " + client.get().uri("/stock")
.retrieve().body(String.class));
System.out.println("version for one request:");
System.out.println(" got " + client.get().uri("/stock").apiVersion("2.0")
.retrieve().body(String.class));
}
}
}
default version:
sends GET /stock API-Version: 1.0
got stock v1
version for one request:
sends GET /stock API-Version: 2.0
got stock v2
told the client where the version goes, andApiVersionInserter.useHeader("API-Version") which version to send when a request names none. The first request went out withdefaultApiVersion("1.0") and received the v1 answer.API-Version: 1.0 on one request overrode the default, and that request received v2..apiVersion("2.0")- The inserter also has
,useQueryParam andusePathSegment , matching the server strategies. The calling code stays the same if the API switches strategies.useMediaTypeParam
The same support exists in WebClient@HttpExchangeMockMvcWebTestClient
Designing versions that last
- Version only breaking changes: adding an optional field to a response or an optional parameter to a request does not break clients that ignore unknown fields. Jackson 3, the default in Spring Boot 4, ignores unknown fields when reading. Save new versions for removals, renames and type changes.
- Prefer baselines: map unchanged endpoints with
once, and add a new method only where a version really changes something."1.0+" - List supported versions explicitly: detection from mappings makes intermediate versions such as 1.1 fail unless some method mentions them. An explicit list documents what the API promises.
- Keep the shapes separate: use separate records per version, as
andOrderV1 do, and convert from one internal model. Version flags inside one record become unreadable quickly.OrderV2 - Plan the end: set deprecation and sunset dates when the new version ships, and remove old mappings after the sunset date.
Choosing a versioning strategy
| Need | Use |
|---|---|
| Internal or partner APIs with stable URLs | Header, spring.mvc.apiversion.use.header=API-Version |
| Versions visible in URLs and caches | Path segment, with a predicate if some paths are not versioned |
| Quick testing from a browser | Query parameter |
| Content negotiation already in use | Media type parameter |
| Clients that send no version | spring.mvc.apiversion.default |
| An endpoint unchanged across versions | A baseline such as version = "1.0+" |
| An endpoint that exists in one version only | A fixed version such as version = "1.2" |
| Warning clients before removal | StandardApiVersionDeprecationHandler |
| Calling a versioned API from Java | RestClientapiVersionInserter |
Versioning sits on top of ordinary request mapping, covered in