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/ in every path, or wrote custom request conditions that read a header. Spring Framework 7.0 made versioning part of request mapping. You add a version attribute to @GetMapping and its siblings, and configure in one place where the version comes from. Spring Boot 4.0 added spring.mvc.apiversion.* properties for that configuration.

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 SemanticApiVersionParser reads major, minor and patch numbers, and sets missing parts to 0, so 2 means 2.0.0.
  • 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.
Where the version can come from
StrategyExample requestSpring Boot propertyBest for
Request headerAPI-Version: 2.0spring.mvc.apiversion.use.headerAPIs used by programs; keeps URLs stable
Query parameter/price?version=2spring.mvc.apiversion.use.query-parameterEasy testing in a browser
Path segment/api/v2/pricespring.mvc.apiversion.use.path-segmentPublic APIs where the version should be visible and cacheable
Media type parameterAccept: application/json;v=2spring.mvc.apiversion.use.media-type-parameterAPIs that already use content negotiation

The programs use Spring Boot 4.1 with Spring Framework 7.0 and spring-boot-starter-webmvc. Each starts on a random port, sends requests with different versions and prints the responses.

Versions in a header

An order API that changed its total from a string to an object is a typical breaking change. The program maps both shapes to the same path, adds a mapping for one exact version, and sends good, missing and bad versions in an API-Version header:

Java
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");
        }
    }
}
Output
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"}
  • version = "1.0+" 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, with "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 2.0+ method. The v2 shape has total as an object.
  • 2 without a minor version was parsed as 2.0.0 and treated exactly like 2.0.
  • With no header, spring.mvc.apiversion.default=1.0 applied and the client got v1. Without a default, a missing version is an error, as the deprecation example below shows.
  • 3.0 is not in the supported list, so Spring answered 400 with Invalid API version: '3.0.0'., before choosing a method. v-two could not be parsed and got the same 400.
  • version = "1.2" without + 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+ mapping; every other endpoint keeps its 1.0+ mapping and serves 2.0 clients unchanged. The supported list matters too: 1.1 works here only because it is listed in spring.mvc.apiversion.supported. By default, Spring detects the supported versions from the mappings. Run without the property, the same program answered 1.1 with 400 Invalid API version: '1.1.0'., because only 1.0, 1.2 and 2.0 appear in mappings.

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:

Java
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");
    }
}
Output
=== 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: ?version=1 and ?version=2 chose the two methods. The parameter is consumed by versioning and does not need a @RequestParam.
  • Path segment: use.path-segment=1 reads the second path segment, counting from 0. The mappings must contain a placeholder in that position, here /api/{version}/price. Both v1 and 2 worked, because the parser ignores a leading letter v.
  • Media type parameter: application/json;v=1 in the Accept header chose v1. The property is a map from media type to parameter name, written as 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 InvalidApiVersionException. For applications that also serve paths without a version, such as a health check, the Java configuration accepts a Predicate<RequestPath> in usePathSegment(index, predicate) to say which paths are versioned.

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:

Java
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));
                }
            }
        }
    }
}
Output
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. Deprecation: @1780272000 is the deprecation date, 1 June 2026, as seconds since 1970, in the format of RFC 9745. Sunset is the date the version will stop working, as an HTTP date, from RFC 8594. Link with rel="sunset" points to the migration guide.
  • The 2.0 response carried none of them.
  • Without a header, the request failed with 400 and API version is required., from MissingApiVersionException. A version is required by default whenever versioning is on and no default is set; setVersionRequired(true) only makes that explicit.
  • 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 Deprecation header, which is far more reliable than an e-mail to client developers. Combine it with metrics on the version each request used, so that you know when the last client has moved on and the old mapping can be deleted. configureApiVersioning and the spring.mvc.apiversion.* properties configure the same ApiVersionConfigurer; properties are simpler, while Java configuration is needed for deprecation handlers, custom parsers and path predicates.

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. RestClient has an ApiVersionInserter that writes the version where the server expects it. An interceptor prints what is actually sent:

Java
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));
        }
    }
}
Output
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
  • ApiVersionInserter.useHeader("API-Version") told the client where the version goes, and defaultApiVersion("1.0") which version to send when a request names none. The first request went out with API-Version: 1.0 and received the v1 answer.
  • .apiVersion("2.0") on one request overrode the default, and that request received v2.
  • The inserter also has useQueryParam, usePathSegment and useMediaTypeParam, matching the server strategies. The calling code stays the same if the API switches strategies.

The same support exists in WebClient, in HTTP service clients declared with @HttpExchange, and in the test clients MockMvc and WebTestClient, so tests can exercise each version without building headers by hand.

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 "1.0+" once, and add a new method only where a version really changes something.
  • 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 OrderV1 and OrderV2 do, and convert from one internal model. Version flags inside one record become unreadable quickly.
  • 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

Versioning choices in Spring Boot 4
NeedUse
Internal or partner APIs with stable URLsHeader, spring.mvc.apiversion.use.header=API-Version
Versions visible in URLs and cachesPath segment, with a predicate if some paths are not versioned
Quick testing from a browserQuery parameter
Content negotiation already in useMedia type parameter
Clients that send no versionspring.mvc.apiversion.default
An endpoint unchanged across versionsA baseline such as version = "1.0+"
An endpoint that exists in one version onlyA fixed version such as version = "1.2"
Warning clients before removalStandardApiVersionDeprecationHandler
Calling a versioned API from JavaRestClient with apiVersionInserter

Versioning sits on top of ordinary request mapping, covered in Spring Boot @RestController. The 400 responses on this page use problem details, described in Spring Boot exception handling.