API Versioning using request headers with Spring framework

API Versioning is a new feature of Spring supported since version 7, which helps us easily add a version for RESTful APIs in the request header, in the path parameter, in the media type parameter, in the query parameter, or a custom version resolver. In this tutorial, I will share with you how to enable API versioning for applications using the Spring framework and how to add a version in the request header for these applications!

First, I will create a new Spring Boot with Spring Web dependency as an example, as follows:

Please note that you must choose Spring Boot version 4 or later! Only Spring Boot version 4 or later uses Spring Framework 7.

I will create a new simple Controller as an example, with the following content:

This controller currently only exposes a simple endpoint “/hello” and I have not defined a version for it yet, as you can see.

To enable versioning for this endpoint in the request header (meaning when requesting to this endpoint, we must pass the version information in the request header), you can:

  • Add a configuration class that implements the WebMvcConfigurer interface and override the configureApiVersioning() method, as follows:

  • Or you can also use the property as follows:

Here, I am configuring to use “X-Api-Version” as the name of the request header to pass the version to the endpoints.

The addSupportedVersions() method is used to specify the versions that our application supports, in addition to the versions declared with the request mappings! If there is any request that has not declared a version, the version of that request will be all the versions declared in the addSupportedVersions() method!

Now, if I run the example application and request to the “/hello” endpoint without passing the version, I will get the “Bad Request” result as follows:

Because I have enabled versioning support, we have to pass the request header “X-Api-Version”, guys!

The result when I pass the request header “X-Api-Version” is as follows:

To specify the version for any endpoint, you can use the version attribute of the annotations @GetMapping, @PostMapping, …. For example:

At this point, the value of the version attribute will be assigned to the value of the request header, and we can request to the endpoint with version 1.1 as follows:

Add Comment