Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

API versioning is the process of managing changes to APIs so that updates do not break existing API users. It allows us to evolve our software while maintaining stability, innovation and backwards compatibility.

The purpose can vary, e.g. removing field(s), changing data format, changing query patterns, altering AuthN/Z, or even changing rate limits.

In this tutorial, we’ll learn various ways to implement API versioning in a Spring application. We’ll focus on the first-class support provided by Spring Boot 4.

2. Example Application

Let’s build an example application in Spring Boot 4.

2.1. Maven Dependencies

First, we need to include the spring-boot-starter and spring-boot-starter-web dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <version>4.0.2</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>4.0.2</version>
</dependency>

With Spring Boot 4/Spring framework 7.0+ release, we can adopt API versioning in a standardized way, without needing a custom implementation.

This can help improve consistency across projects, reducing boilerplate code and maintenance overhead.

2.2. Implement the REST API

We’ll implement a REST API to fetch some data using a ProductDto model:

public record ProductDto(String id, String name, String desc, double price) {
}

First, we’ll implement a GET /products/{id} endpoint to fetch a single product:

@RestController
@RequestMapping(path = "/api/products")
public class ProductController {

    @GetMapping(value = "/{id}")
    public ProductDto getProductById(@PathVariable String id) {
        LOGGER.info("Get Product for id {}", id);
        return productsMap.get(id);
    }
}

Next, we’ll introduce a breaking change to the above data model.

3. Implement API Versioning in Spring Boot 4

Let’s imagine we need to return a different response model. Instead of updating the existing API, which may break our existing consumers, we can introduce a new API version.

We can choose which API version to call with the following versioning strategies:

  • Header Versioning – Uses a version header in the request
  • Query Parameter Versioning – Uses a version field in the request query parameter
  • Content Negotiation Versioning – Defines different versions using the Accept header as a content negotiation MIME type
  • URI Path Versioning – Set the version identifier in the URI path

While there are other approaches, like changing the hostname/sub-domain or request/response-driven versioning, we’ll focus on the above approaches.

3.1. Header Versioning

With header versioning, we include a custom version header in the request. It’s an elegant and effective approach that is REST-compliant and doesn’t pollute the URI path with a version. Some downsides are that it’s harder to discover, debug and potential client-side cache issues, as clients use only the URI path to cache responses.

First, we’ll remove the desc field in the ProductDtoV2 model:

public record ProductDtoV2(String id, String name, double price) {
}

The annotations like RequestMapping, GetMapping, PostMapping and others now have a version attribute to specify the API version.

We’ll specify the version field in the ProductController class and add another method for the new API:

@GetMapping(value = "/{id}", version = "1.0")
public ProductDto getProductById(@PathVariable String id) {
    LOGGER.info("Get Product version 1 for id {}", id);
    return productsMap.get(id);
}

@GetMapping(value = "/{id}", version = "2.0")
public ProductDtoV2 getProductV2ById(@PathVariable String id) {
    LOGGER.info("Get Product version 2 for id {}", id);
    return productsV2Map.get(id);
}

In the version field, we include only the major and minor numbers, and not the complete semantic versioning.
The client can call the API with the major version only, as the minor and patch numbers rarely matter.

Additionally, if we prefer the functional-style API routes, we’ll specify the version with the RouterFunctions.route‘s GET method:

@Bean
public RouterFunction<ServerResponse> productRoutes() {
    return RouterFunctions.route()
      .GET("/api/products/{id}", version("1.0"),
        req -> ServerResponse.ok()
          .body(productsMap.get(req.pathVariable("id"))))
      .GET("/api/products/{id}", version("2.0"),
        req -> ServerResponse.ok()
          .body(productsV2Map.get(req.pathVariable("id"))))
      .build();
}

To enable header versioning in our Spring application, we’ll set the required configuration on the ApiVersionConfigurer class.

We’ll implement the WebConfig class by implementing the WebMvcConfigurer interface to configure the versioning strategy:

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureApiVersioning(ApiVersionConfigurer configurer) {
        configurer.addSupportedVersions("1.0", "2.0")
          .setDefaultVersion("1.0")
          .useRequestHeader("X-API-Version");
    }
}

In the configuration above, we specify the header version name, supported versions, and a default version.

The default version will be used if the version header is not supplied, ensuring backward compatibility.

Alternatively, we can specify the API version configuration in the application.properties file:

spring.mvc.apiversion.supported=1.0,2.0
spring.mvc.apiversion.default=1.0
spring.mvc.apiversion.enabled=true
spring.mvc.apiversion.use.header=X-API-Version

We can either use the Java-based configurations or the application.properties, but should not mix them both together. However, if they are mixed, the Java-based configuration will take precedence over the application.properties.

Internally, Spring uses the ApiVersionParser interface, which is in turn used by the main ApiVersionStrategy interface to parse the raw version value extracted from the request into a specific format.
It supports both semantic versioning and range-based versioning by implementing a custom parser.
With the range-based versioning, the client specifies a version range such as [1, 3], instead of a fixed version.

3.2. Query Param Versioning

As in the previous approach, we’ll specify the version field in the ProductController‘s methods.

We’ll specify similar configuration to the ApiVersionConfigurer class to enable query param versioning:

@Override
public void configureApiVersioning(ApiVersionConfigurer configurer) {
    configurer
      .addSupportedVersions("1.0", "2.0")
      .setDefaultVersion("1.0")
      .useQueryParam("version");
}

Alternatively, we can set the apiversions.use.query-parameter property in our application.properties:

spring.mvc.apiversion.use.query-parameter=version

The above approach is good for internal applications and testing. Though the downside is that it’s less explicit and requires a parameter, which are more typically used for other purposes, e.g. filtering and pagination.

3.3. Content Negotiation Versioning

The content negotiation versioning approach is a sophisticated way to version APIs using the MIME (Multipurpose Internet Mail Extensions) media type.

This also doesn’t change the URI path, making it REST-compliant and providing the vendor-specific data formats using the Accept request header.

First, we’ll include the vendor-specific media type with the version field in both ProductController class methods:

@GetMapping(value = "/{id}", version = "2.0",
  produces = "application/vnd.baeldung.product+json")
public ProductDtoV2 getProductV2ByIdCustomMedia(@PathVariable String id) {
    LOGGER.info("Get Product with custom media version 2 for id {}", id);
    return productsV2Map.get(id);
}

Then, we’ll configure the supported custom media type with a version parameter in the WebConfig class:

@Override
public void configureApiVersioning(ApiVersionConfigurer configurer) {
    configurer
      .addSupportedVersions("1.0", "2.0")
      .setDefaultVersion("1.0")
      .useMediaTypeParameter(MediaType.parseMediaType("application/vnd.baeldung.product+json"),
        "version");
}

Alternatively, we can configure the custom media type and version in our application.properties:

spring.mvc.apiversion.use.media-type-parameter[application/vnd.baeldung.product+json]=version

The above custom media type should match the controller’s configured media type.

3.4. URI Versioning (Path-Segment Based)

While the URI path versioning is a simple, cache-friendly and practical approach, it can clutter the code and pollute the resource URI path with the version.

To natively support path-based versioning in the URI, we’ll include the version tag in the controller class.

We’ll include the version segment with a predefined prefix in the ProductController class:

@RestController
@RequestMapping(path = "/api/v{version}/products")
public class ProductController {
}

Note that in the above code, we’ve included the path segment’s version prefix as per convention. However, Spring does not mandate a prefix.

We’ll also include the required path segment index in the WebConfig class:

@Override
public void configureApiVersioning(ApiVersionConfigurer configurer) {
    configurer
      .usePathSegment(1)
      .setDefaultVersion(null)
      .addSupportedVersions("1.0", "2.0");
}

Alternatively, we can configure the path-segment index in our application.properties file:

spring.mvc.apiversion.use.path-segment=1

In the config above, the path-segment index is set to 1, which matches the index of the version tag in the ProductController class.

We should note that by configuring the path segment versioning, we override any other approaches if defined.

Spring resolves the request version by implementing the ApiVersionResolver’s resolveVersion method as per the configured versioning.

4. Test the APIs

We’ll implement integration tests to ensure the APIs route as expected.

4.1. Header Versioning Testing

We’ll test the /products endpoint using the RestTestClient instance.

First, we’ll configure the RestTestClient instance with the header version field name:

void setUp() {
    restTestClient = RestTestClient
      .bindToServer()
      .baseUrl("http://localhost:" + port)
      .apiVersionInserter(ApiVersionInserter.useHeader("X-API-Version"))
      .build();
}

Then, let’s write a test to fetch version 2 of the Product data:

@Test
void givenProductExists_whenProductIsCalledWithHeaderVersion2_thenReturnValidProduct() {
    restTestClient.get()
      .uri("/api/products/1001")
      .apiVersion(2)
      .exchange()
      .expectStatus().isOk()
      .expectBody()
      .jsonPath("$.name").isEqualTo("apple")
      .jsonPath("$.desc").doesNotExist()
      .jsonPath("$.price").isEqualTo(1.99);
}

In the code above, we’re passing the version number using the apiVersion method.

We expect to get the HTTP 400 Bad Request error if an invalid version is requested:

{
    "timestamp": "2026-02-10T10:40:50.562Z",
    "status": 400,
    "error": "Bad Request",
    "path": "/api/products/1001"
}

Next, we’ll implement similar tests for the other approaches.

4.2. Query Param Versioning Testing

First, we’ll set up the RestTestClient with the version query param name:

void setUp() {
    restTestClient = RestTestClient
      .bindToServer()
      .baseUrl("http://localhost:" + port)
      .apiVersionInserter(ApiVersionInserter.useQueryParam("version"))
      .build();
}

We’ll test the /products endpoint by passing the apiVersion parameter:

@Test
void givenProductExists_whenProductIsCalledWithQueryParamVersion2_thenReturnValidProductV2() {
    restTestClient.get()
      .uri("/api/products/1001")
      .apiVersion(2)
      .exchange()
      .expectStatus()
      .isOk()
      .expectBody()
      .jsonPath("$.name").isEqualTo("apple")
      .jsonPath("$.desc").doesNotExist()
      .jsonPath("$.price").isEqualTo(1.99);
}

The above test confirms that version 2 of the API is called.

4.3. Content Negotiation Versioning Testing

We’ll test the /products endpoint by using the custom media type with the version field in the Accept header:

@Test
void givenProductExists_whenProductIsCalledWithValidMediaTypeVersion_thenReturnValidProduct() {
    restTestClient.get()
      .uri("/api/products/1001")
      .accept(MediaType.valueOf("application/vnd.baeldung.product+json;version=1"))
      .exchange()
      .expectStatus()
      .isOk()
      .expectHeader().contentType("application/vnd.baeldung.product+json;version=1")
      .expectBody()
      .jsonPath("$.name").isEqualTo("apple")
      .jsonPath("$.desc").isEqualTo("apple_desc")
      .jsonPath("$.price").isEqualTo(1.99);
}

In the code above, we retrieve the same product and matching content type as requested.

4.4. URI Versioning Testing

Now, we’ll test the /v1/products endpoint using the path segment version.

First, we’ll configure the RestTestClient to specify the path segment index:

void setUp() {
    restTestClient = RestTestClient
      .bindToServer()
      .baseUrl("http://localhost:" + port)
      .apiVersionInserter(ApiVersionInserter.usePathSegment(1))
      .build();
}

We’ll set the apiVersion to v1:

@Test
void givenProductExists_whenGetProductIsCalledWithPathSegmentV1_thenReturnValidProduct() {
    restTestClient.get()
      .uri("/api/products/1001")
      .apiVersion("v1")
      .exchange()
      .expectStatus()
      .isOk()
      .expectBody()
      .jsonPath("$.name").isEqualTo("apple")
      .jsonPath("$.desc").isEqualTo("apple_desc")
      .jsonPath("$.price").isEqualTo(1.99);
}

In the code above, we can include the path segment version into the /api/v1/products/1001 URI, instead of using the apiVersion method.

We recommend not mixing different versioning strategies, as it can create conflict and confusion in the API routing logic.

5. Conclusion

In this article, we’ve learned different ways to implement API versioning in a Spring Boot application. We’ve implemented header-based, query param, media type and path segment versioning using Spring’s native version field and ApiVersionConfigurer class. Finally, we tested the APIs with the RestTestClient class.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

2 Comments
Oldest
Newest