eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

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 – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

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.

As always, the example code can be found over on GitHub.

Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

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 – LS – NPI (cat=REST)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments