Integrating Swagger/OpenAPI with Spring Boot 3: A Comprehensive Guide

Naveen Metta
4 min readJun 12, 2024

--

credit goes to the owner : https://swagger.io/tools/swagger-ui/
source : swagger.io

Spring Boot 3 brings a host of new features and improvements. One essential integration for modern API development is with Swagger/OpenAPI, which simplifies API documentation and testing. This guide will walk you through the steps to seamlessly integrate Swagger/OpenAPI with your Spring Boot 3 application, complete with detailed explanations and Java code examples.

Why Swagger/OpenAPI?

Swagger and OpenAPI are powerful tools for generating interactive API documentation. They provide a standardized way to describe and visualize REST APIs, making it easier for developers to understand and interact with your services.

Getting Started

Step 1: Set Up Your Spring Boot 3 Project

First, create a new Spring Boot project using Spring Initializr (https://start.spring.io/). Select the following dependencies:

  • Spring Web
  • Spring Boot DevTools
  • Spring Data JPA
  • H2 Database (for simplicity)
  • Spring Boot Actuator (optional for monitoring)

Generate and download the project. Unzip it and open it in your favorite IDE.

Step 2: Add Swagger Dependencies

To integrate Swagger/OpenAPI, you need to add the necessary dependencies to your pom.xml file. Add the following dependencies:

<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.14</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-data-rest</artifactId>
<version>1.6.14</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-kotlin</artifactId>
<version>1.6.14</version>
</dependency>

These dependencies will pull in everything you need to integrate Swagger/OpenAPI into your Spring Boot project.

Step 3: Configure Swagger

Create a configuration class to customize Swagger settings. In src/main/java/com/example/demo/config, create a file named SwaggerConfig.java:

package com.example.demo.config;

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.Contact;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SwaggerConfig {

@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("Spring Boot 3 API")
.version("1.0")
.description("Sample Spring Boot 3 project with Swagger/OpenAPI integration")
.contact(new Contact()
.name("John Doe")
.email("johndoe@example.com")
.url("https://example.com")));
}
}

This configuration sets up the basic information for your API documentation.

Step 4: Annotate Your Controllers

To generate API documentation, you need to annotate your controllers. Here’s an example controller:

package com.example.demo.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Tag(name = "Sample API", description = "Sample operations for demonstration")
public class SampleController {

@GetMapping("/hello")
@Operation(summary = "Say Hello", description = "Returns a greeting message")
public String sayHello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello, %s!", name);
}

@GetMapping("/hello/{name}")
@Operation(summary = "Say Hello with Path Variable", description = "Returns a greeting message with path variable")
public String sayHelloPath(@PathVariable String name) {
return String.format("Hello, %s!", name);
}
}

The @Operation annotation provides metadata for the API methods, and the @Tag annotation groups related methods.

Testing Your API

Start your Spring Boot application and navigate to http://localhost:8080/swagger-ui.html. You should see the interactive Swagger UI with the documented endpoints.

Advanced Configuration

Customizing Swagger UI Path

If you want to change the default path of Swagger UI, you can add the following properties to your application.properties file:

springdoc.swagger-ui.path=/api-docs
springdoc.api-docs.path=/v3/api-docs

Securing the API Documentation

If your API requires security, you can configure Swagger to include authentication details. Here’s an example with basic authentication:

package com.example.demo.config;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SwaggerConfig {

@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.components(new Components()
.addSecuritySchemes("basicScheme", new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.scheme("basic")))
.addSecurityItem(new SecurityRequirement().addList("basicScheme"))
.info(new Info()
.title("Spring Boot 3 API")
.version("1.0")
.description("Sample Spring Boot 3 project with Swagger/OpenAPI integration"));
}
}

Handling Different Environments

You might want different configurations for different environments (e.g., dev, prod). Here’s how you can handle it using Spring profiles.

Step 1: Define Profiles

In src/main/resources, create application-dev.properties and application-prod.properties with environment-specific properties.

Step 2: Use Profiles in Configuration

In your SwaggerConfig.java, you can conditionally apply settings based on the active profile:

package com.example.demo.config;

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Configuration
public class SwaggerConfig {

@Value("${spring.profiles.active}")
private String activeProfile;

@Bean
@Profile("dev")
public OpenAPI devOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("Spring Boot 3 API - Dev")
.version("1.0")
.description("Sample Spring Boot 3 project with Swagger/OpenAPI integration (Development)"));
}

@Bean
@Profile("prod")
public OpenAPI prodOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("Spring Boot 3 API - Prod")
.version("1.0")
.description("Sample Spring Boot 3 project with Swagger/OpenAPI integration (Production)"));
}
}

Conclusion

Integrating Swagger/OpenAPI with Spring Boot 3 is straightforward and highly beneficial for API development. With the steps outlined above, you can set up comprehensive API documentation that is easy to navigate and understand. This integration not only improves the developer experience but also helps in maintaining and scaling your APIs efficiently.

For more information, you can check out the SpringDoc documentation and the OpenAPI Specification.

--

--

Naveen Metta

I'm a Full Stack Developer with 2.5 years of experience. feel free to reach out for any help : mettanaveen701@gmail.com