Java4Shell (CVE-2026-114938) is fixed in Liberica JDK

See details
Posts

How to Use Swagger (OpenAPI) in Spring Boot 3 and 4

Updated

Catherine Edelveis

22

To add Swagger to a Spring Boot app, add the springdoc-openapi-starter-webmvc-ui dependency (version 3.x for Spring Boot 4, 2.x for Spring Boot 3) and start the app. Swagger UI opens at http://localhost:8080/swagger-ui/index.html, and the OpenAPI JSON is at /v3/api-docs.

This step-by-step tutorial will guide you through integrating Swagger (based on the OpenAPI 3.x specification) into a Spring Boot project.

By the way, if you deploy Spring Boot services to the cloud, check out Alpaquita Containers tailor-made for Spring Boot: they can help you save up to 30% RAM!

And did you know that you can easily reduce startup and warmup times of your Spring Boot services from minutes to milliseconds by using Java with CRaC support? Give it a try!

What is Swagger?

Swagger is a set of tools that help developers to create, edit, and use API documentation according to the OpenAPI specification. With Swagger, it is no longer necessary to manually write lengthy API docs: the solution is capable of reading the structure of the API you defined in the annotations of your code and automatically converting it into API specification.

What is more, Swagger provides a user interface that generates interactive API documentation that lets users test the API calls in the browser.

Main Swagger components are:

  • Swagger Editor for writing and editing API specs,
  • Swagger UI for creating interactive API documentation,
  • Swagger Codegen for generating server stubs or client libraries for your API.

Swagger vs OpenAPI

Both terms, Swagger and OpenAPI, are used in the context of API documentation, but they are not the same. OpenAPI is a standard specification for describing API, and Swagger helps to create API docs in line with this specification.

So, is Swagger now called OpenAPI? Partly: the specification once called Swagger is now the OpenAPI Specification, Swagger is the collection of tools around it, and springdoc generates the OpenAPI description from your Spring application code.

For example, BellSoft uses REST Discovery API based on OpenAPI specification to provide metadata about its products (version, build number, architecture, features, etc.) By querying this information, users can get a comprehensive understanding of product characteristics.

Integrating Swagger into a Spring Boot project

Prerequisites

  • JDK 25 (LTS). I will use Liberica JDK, recommended by the Spring team.
  • Spring Boot 4.1.2
  • Maven
  • Your favorite IDE (I will use IntelliJ IDEA)

Create a sample REST API project

Skip this step if you want to use your own project. You can follow along or implement the examples from the tutorial into your application accordingly.

The code for the demo project used below is available on GitHub.

Our demo Spring Boot application will expose REST APIs for managing employees. The Employee will have id, first name, and last name. Our APIs will allow for getting a list of all employees, getting one employee, adding a new employee, updating the existing employee, and deleting an employee according to the following schema:

Method

URL

Action

GET

/employees

Get a list of all employees

GET

/employees/{employeeId}

Get one employee by id

POST

/employees

Add an employee

PUT

/employees

Update an employee

DELETE

/employees/{employeeId}

Delete an employee

Head to Spring Initializr to create a skeleton of your project. Select Java, Maven, define a project name (I have openapidemo), and choose Spring Boot 4.1.2 and Java 25.

Select H2 Database, Spring Web, Validation, Lombok, and Spring Data JDBC. H2 runs in memory, so the demo needs no separate database server. DevTools is optional and restarts the app when compiled classes change.

Generate the project and open it in your IDE.

Let’s keep the structure simple and yet close to production-like setup. First, we will need the basic class Employee:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Employee {

    @Id
    private int id;
    private String firstName;
    private String lastName;


    public Employee(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

Let’s create DTOs and map them with MapStruct. If you started from Spring Initializr, add the MapStruct dependency and version and copy the Maven compiler configuration. It registers the MapStruct and Lombok processors plus lombok-mapstruct-binding, which lets MapStruct see the members Lombok generates.

I won't go into details of working with MapStruct here. You can read more about creating DTOs with Mapstruct in my previous guide.

The code for DTOs and Mapper:

@Builder
public record EmployeeDto(int id,
                          String firstName,
                          String lastName) {
}


@Builder
public record NewEmployeeDto(String firstName,
                             String lastName) {
}


@Mapper(unmappedTargetPolicy = org.mapstruct.ReportingPolicy.IGNORE,
        componentModel = "spring")
public interface EmployeeMapper {

    EmployeeDto mapToEmployeeDto(Employee employee);
    Employee mapToEmployee(EmployeeDto employeeDto);
    Employee mapToEmployee(NewEmployeeDto employeeDto);

}

MapStruct generates the implementation of this interface at compile time and registers it as a Spring bean.

Next, let's create EmployeeController, EmployeeRepository interface, and EmployeeService.

Populate the classes as shown below. I have also added a custom NotFoundException with relevant ErrorHandler.

public interface EmployeeRepository extends ListCrudRepository<Employee, Integer> { }
@Service
public class EmployeeService {


    private final EmployeeRepository employeeRepository;
    private final EmployeeMapper mapper;


    public EmployeeService(EmployeeRepository employeeRepository, EmployeeMapper employeeMapper) {
        this.employeeRepository = employeeRepository;
        this.mapper = employeeMapper;
    }


    public List<EmployeeDto> findAll() {
        return employeeRepository.findAll()
                .stream()
                .map(mapper::mapToEmployeeDto)
                .toList();
    }


    public EmployeeDto findById(int id) {
        Optional<Employee> employee = employeeRepository.findById(id);
        if (employee.isEmpty()) {
            throw new NotFoundException("Employee not found with id: " + id);
        }
        return mapper.mapToEmployeeDto(employee.get());
    }


    public EmployeeDto save(NewEmployeeDto employeeDto) {
        Employee employee = mapper.mapToEmployee(employeeDto);
        return mapper.mapToEmployeeDto(employeeRepository.save(employee));
    }


    public EmployeeDto update(EmployeeDto employeeDto) {
        Employee employee = mapper.mapToEmployee(employeeDto);
        return mapper.mapToEmployeeDto(employeeRepository.save(employee));
    }


    public void deleteById(int id) {
        if (!employeeRepository.existsById(id)) {
            throw new NotFoundException("Employee not found with id: " + id);
        }
        employeeRepository.deleteById(id);
    }
    
}
@RestController
public class EmployeeController {


    private final EmployeeService employeeService;


    public EmployeeController(EmployeeService service) {
        this.employeeService = service;
    }


    @GetMapping("/employees")
    public List<EmployeeDto> findAllEmployees() {
        return employeeService.findAll();
    }


    @GetMapping("/employees/{employeeId}")
    public EmployeeDto getEmployee(@Parameter(
            description = "ID of employee to be retrieved",
            required = true)
                                   @PathVariable int employeeId) {


        return employeeService.findById(employeeId);
    }


    @PostMapping("/employees")
    public EmployeeDto addEmployee(@RequestBody NewEmployeeDto employee) {
        return employeeService.save(employee);
    }


    @PutMapping("/employees")
    public EmployeeDto updateEmployee(@RequestBody EmployeeDto employee) {
        return employeeService.update(employee);
    }


    @DeleteMapping("/employees/{employeeId}")
    public String deleteEmployee(@PathVariable int employeeId) {
        employeeService.deleteById(employeeId);
        return "Deleted employee with id: " + employeeId;
    }


}

Now, let’s provide a database schema. Create a schema.sql file in the resources directory with the following content:

CREATE TABLE IF NOT EXISTS employee (
    id         INT AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(20) NOT NULL,
    last_name  VARCHAR(50) NOT NULL
);

Next, let’s populate our database instance with some data. Create the data.sql file in resources with the following content:

delete from employee;
insert into employee (first_name, last_name) values ('John', 'Doe');
insert into employee (first_name, last_name) values ('Jane', 'Smith');

The last thing to do is to add several properties to the application.properties file because we are performing a script-based initialization:

spring.sql.init.schema-locations=classpath*:schema.sql
spring.sql.init.data-locations=classpath*:data.sql
spring.sql.init.mode=always

Finally, let’s verify that the app is functioning as desired. Run the application.

You should see the following result at http://localhost:8080/employees:

[
  {
    "id": 1,
    "firstName": "John",
    "lastName": "Doe"
  },
  {
    "id": 2,
    "firstName": "Jane",
    "lastName": "Smith"
  }
]

That’s it! Our minimalistic CRUD application is ready for experiments.

Add springdoc-openapi dependency

To work with Swagger, we need the springdoc-openapi library that helps to generate OpenAPI-compliant API documentation for Spring Boot projects. The library supports Swagger UI and other useful features such as OAuth2 and GraalVM Native Image.

Which version you need depends on your Spring Boot line. Spring Boot 4 is supported by springdoc 3.x, and even within 3.x, the minor versions follow Boot's minor versions:

Spring Boot

springdoc-openapi

Notes

4.1.x

3.1.x–3.2.x

Used in this tutorial: springdoc-openapi-starter-webmvc-ui 3.2.0

4.0.x

3.0.x

Don't assume every 3.x release works with Boot 4.0

3.x

2.x

For Spring Boot 3.5.x, use 2.10.0

Migrating from Boot 3? Bump springdoc together with Boot. Our Spring Boot 3 to Spring Boot 4 migration guide covers the rest.

Add the following dependency for springdoc-openapi to your pom.xml file:

<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
  <version>3.2.0</version>
</dependency>

Or, if you use Gradle (Kotlin DSL), to build.gradle.kts:

dependencies {
    implementation("org.springdoc:springdoc-openapi-starter-webmvc-ui:3.2.0")
}

Building a reactive app on WebFlux? Use springdoc-openapi-starter-webflux-ui instead. The starter names are the same on Boot 3. For earlier Boot 3 minors, consult the springdoc 2.x compatibility matrix.

That’s all, the default setup requires no additional configuration! Customization is available, though, and we'll get to it shortly.

Generate API documentation

springdoc inspects your controllers at runtime and serves the OpenAPI document over HTTP. Start the app and open http://localhost:8080/v3/api-docs for JSON or http://localhost:8080/v3/api-docs.yaml for YAML.

Integrate Swagger UI

The beauty about springdoc-openapi library dependency is that it already includes Swagger UI, so we don’t have to configure the tool separately!

You can access Swagger UI at http://localhost:8080/swagger-ui/index.html, where you will see a beautiful user interface to interact with your endpoints (or similar to the one on the screenshot if you are using your project):

Swagger UI

How to open Swagger UI: default URL, custom path, Spring Security

With the default setup, springdoc gives you four URLs:

  • http://localhost:8080/swagger-ui/index.html: the Swagger UI entry point.
  • http://localhost:8080/swagger-ui.html: the default value of springdoc.swagger-ui.path. It redirects to /swagger-ui/index.html.
  • http://localhost:8080/v3/api-docs: the generated OpenAPI description in JSON.
  • http://localhost:8080/v3/api-docs.yaml: the same description in YAML.

These are defaults for the usual local setup: a different port, a context path, app routing, or security rules change what you need to visit.

Let's move things around in application.properties:

server.servlet.context-path=/hr
springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/docs
  • server.servlet.context-path prefixes every URL of the app, controllers included: /employees becomes /hr/employees.
  • springdoc.api-docs.path moves the OpenAPI document to http://localhost:8080/hr/api-docs (and /hr/api-docs.yaml). /v3/api-docs no longer serves it.
  • springdoc.swagger-ui.path changes only the entry point: http://localhost:8080/hr/docs redirects to /hr/swagger-ui/index.html, and the UI files stay under /swagger-ui/**.

Write Spring Security matchers relative to the application context, such as /api-docs/** with the /hr prefix omitted.

Swagger UI not loading

The usual symptoms rarely have a single cause:

  • 404 or Whitelabel Error Page. The Whitelabel page is just Spring Boot's default error rendering. Usually the URL doesn't match what the app serves: a forgotten context path, customized springdoc paths, a missing dependency, or a springdoc line that doesn't match your Boot version (see the table above).
  • "Failed to load remote configuration". The UI page loaded, but the browser couldn't fetch its configuration (/v3/api-docs/swagger-config) or the document itself. Typically, Spring Security blocks the docs endpoints, or a proxy or context path sends the UI to the wrong URL.

First, open /v3/api-docs or your configured JSON URL directly. If it fails, check the context path, springdoc properties, and access rules. To try the optional example below in the demo, add org.springframework.boot:spring-boot-starter-security. Spring Boot secures the app by default once the starter is present.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(
                                "/v3/api-docs/**",
                                "/v3/api-docs.yaml",
                                "/swagger-ui/**",
                                "/swagger-ui.html"
                        ).permitAll()
                        .anyRequest().authenticated()
                )
                .httpBasic(Customizer.withDefaults());
        return http.build();
    }
}

The permitAll() rules open the docs. Employee endpoints still require authentication, and write requests remain subject to CSRF protection. The /** pattern covers the base JSON route and swagger-config. YAML needs its own matcher. For the custom paths above, use /api-docs/**, /api-docs.yaml, /swagger-ui/**, and /docs.

Whether the docs should be public in production is a separate question, and often the answer is no: keep them behind authentication, or switch them off with springdoc.api-docs.enabled=false and springdoc.swagger-ui.enabled=false.

Document the API with OpenAPI annotations

Right now, our API documentation is not very informative. We can extend it with the help of annotations added to the application code. Below is the summary of the most common ones.

Add Swagger API description

First of all, let’s include some essential data about the API, such as name, description, and author contacts. For that purpose, create an OpenAPIConfiguration class and fill in the following code:

@Configuration
public class OpenAPIConfiguration {


   @Bean
   public OpenAPI defineOpenApi() {
       Contact myContact = new Contact();
       myContact.setName("Jane Doe");
       myContact.setEmail("[email protected]");


       Info information = new Info()
               .title("Employee Management System API")
               .version("1.0")
               .description("This API exposes endpoints to manage employees.")
               .contact(myContact);
       return new OpenAPI().info(information);
   }
}

Run the app and check the API title and description in Swagger UI. The repository also sets an explicit server URL. If you use its configuration with the /hr example, remove the explicit server or include /hr in its URL so “Try it out” reaches the correct endpoints.

API description

Jakarta Bean Validation

The springdoc-openapi library supports Jakarta Bean Validation (@NotNull, @Min, @Max, and @Size), so when we add these annotations to our code, the additional schema documentation will be automatically generated. The annotations live in the jakarta.validation package, which comes with the spring-boot-starter-validation dependency (Validation in Spring Initializr).

Let’s specify them in our DTOs: they are what the API accepts and returns, so they define the request and response schemas (more on that in the ultimate guide to using DTOs with Spring Boot).

import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Builder;

@Builder
public record NewEmployeeDto(@NotNull @Size(min = 1, max = 20) String firstName,
                             @NotNull @Size(min = 1, max = 50) String lastName) {
}

Add the same name constraints to EmployeeDto. Spring MVC enforces them when you import jakarta.validation.Valid and add @Valid to both request bodies:

@PostMapping("/employees")
public EmployeeDto addEmployee(@Valid @RequestBody NewEmployeeDto employee) {
    return employeeService.save(employee);
}

@PutMapping("/employees")
public EmployeeDto updateEmployee(@Valid @RequestBody EmployeeDto employee) {
    return employeeService.update(employee);
}

When you recompile your app, you will see that the Schemas section contains the specified info:

API Schema

@Tag annotation

The @Tag annotation can be applied at class or method level and is used to group the APIs in a meaningful way.

For instance, let’s add this annotation to our GET methods:

@Tag(name = "get", description = "GET methods of Employee APIs")
@GetMapping("/employees")
public List<EmployeeDto> findAllEmployees() {
    return employeeService.findAll();
}


@Tag(name = "get", description = "GET methods of Employee APIs")
@GetMapping("/employees/{employeeId}")
public EmployeeDto getEmployee(
        @PathVariable int employeeId) {


    return employeeService.findById(employeeId);
}

Both methods share the tag, so they share the description too: one tag can have only one description in the generated document.

You will see that APIs are now grouped differently:

API grouping

@Operation annotation

The @Operation annotation enables the developers to provide additional information about a method, such as summary and description.

Let’s update our updateEmployee() method:

@Operation(summary = "Update an employee",
        description = "Update an existing employee. Returns the updated employee DTO with its ID, first name, and last name.")
@PutMapping("/employees")
public EmployeeDto updateEmployee(@Valid @RequestBody EmployeeDto employee) {
    return employeeService.update(employee);
}

The API description in Swagger UI is now a little more informative:

Endpoint description

@ApiResponses annotation

The @ApiResponses annotation helps to add information about responses available for the given method. Each response is specified with @ApiResponse, for instance

@ApiResponses({
        @ApiResponse(responseCode = "200", description = "Employee deleted",
                content = @Content(mediaType = "text/plain",
                        schema = @Schema(implementation = String.class,
                                example = "Deleted employee with id: 1"))),
        @ApiResponse(responseCode = "404", description = "Employee not found",
                content = @Content(mediaType = "application/json",
                        schema = @Schema(implementation = ErrorResponse.class)))})
@DeleteMapping("/employees/{employeeId}")
public String deleteEmployee(@PathVariable int employeeId) {
    employeeService.deleteById(employeeId);
    return "Deleted employee with id: " + employeeId;
}

Make sure the responses describe what the method really returns: here, a plain-text confirmation and the ErrorResponse from our error handler. The compiler won't catch a wrong schema for you.

After you recompile the Controller class, the data on responses will be automatically generated:

API responses

@Parameter annotation

The @Parameter annotation can be used on a method parameter to define parameters for the operation. For example,

public EmployeeDto getEmployee(@Parameter(
        description = "ID of employee to be retrieved",
        required = true)
                               @PathVariable int employeeId) {
    return employeeService.findById(employeeId);
}

Here, the description element provides additional data on parameter purpose, and required is set to true signifying that this parameter is mandatory.

And here’s how it looks in Swagger UI:

Endpoint parameters

FAQ

Is Swagger now called OpenAPI?

OpenAPI is the name of the specification formerly called Swagger. The Swagger tools include Swagger UI, which displays the OpenAPI description that springdoc generates.

What is the Swagger UI URL in Spring Boot?

By default, it's http://localhost:8080/swagger-ui/index.html, and /swagger-ui.html redirects there. A different port, server.servlet.context-path, or springdoc.swagger-ui.path changes the URL you need to open.

Which springdoc version should I use with Spring Boot 4?

Use springdoc-openapi 3.x: 3.1.x–3.2.x for Spring Boot 4.1.x (this tutorial uses Boot 4.1.2 with 3.2.0) and 3.0.x for Spring Boot 4.0.x.

What is the difference between Swagger and Postman?

Swagger documents an API from its OpenAPI description and lets you try the endpoints in the browser. Postman is an API client for building, saving, and automating requests and test collections. They aren't mutually exclusive: Postman can import an OpenAPI document.

Where can I find the OpenAPI JSON?

At http://localhost:8080/v3/api-docs by default, and the YAML version is at /v3/api-docs.yaml. If you set springdoc.api-docs.path or a context path, the document moves accordingly.

Conclusion

As you can see, writing APIs with Swagger is extremely convenient. The solution enables declarative and consistent API documentation without laborious manual effort. As a result, it accelerates the development process and minimizes the risk of errors, so you should definitely integrate it into your workflow! And on Spring Boot 4, it is the same story: pick springdoc 3.x, and the starter names and default URLs stay the same as before.

And if you are looking to optimize resource consumption of your containerized Spring Boot apps, try out Alpaquita Containers tailor-made for Spring Boot and helping to achieve up to 30 % RAM savings!

 

Subcribe to our newsletter

figure

Read the industry news, receive solutions to your problems, and find the ways to save money.

Further reading