Integrating Spring Boot with Swagger / OpenAPI

Swagger, now known as OpenAPI, is a powerful framework for designing, building, documenting, and consuming REST APIs. Integrating Swagger into a Spring Boot project allows developers to automatically generate API documentation based on controller definitions. This improves visibility and understanding of API functionality, making it easier for teams and consumers to interact with your application.

This guide covers how to integrate Swagger/OpenAPI with Spring Boot, from setting up dependencies to customizing the UI and securing your API documentation.

Table of Contents

  1. Adding Swagger Dependencies
  2. Annotating Controllers
  3. Customizing UI and Endpoints
  4. Securing API Docs
  5. External Resources for Further Learning
  6. Final Thoughts

Adding Swagger Dependencies

To use Swagger/OpenAPI in a Spring Boot application, add the Springdoc OpenAPI library to your project. Springdoc OpenAPI is the recommended way to integrate Swagger/OpenAPI with Spring Boot.

Maven Dependency

Add the following dependency in your pom.xml:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.2.0</version> <!-- Use the latest version -->
</dependency>

Gradle Dependency

If you’re using Gradle, add this to your build.gradle file:

implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'

What This Provides

  • Access to automatically generated API documentation at /swagger-ui.html.
  • OpenAPI 3.0 specifications under /v3/api-docs.

After adding these dependencies and starting your Spring Boot application, your API documentation will be live at:

  • Swagger UI URL: http://localhost:8080/swagger-ui.html
  • API Docs URL (JSON): http://localhost:8080/v3/api-docs

Optional Dependencies

You can add the following dependencies for extra features:

  • Spring Security Integration: <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-security</artifactId> <version>2.2.0</version> </dependency>
  • Spring WebFlux Support: <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webflux-ui</artifactId> <version>2.2.0</version> </dependency>

Annotating Controllers

Swagger/OpenAPI leverages annotations to generate documentation directly from your controller classes. These annotations come from the io.swagger.v3.oas.annotations package.

Adding Annotations

Here’s how to annotate a REST controller for Swagger documentation.

UserController.java

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.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
@Tag(name = "User Controller", description = "Endpoints for managing users")
public class UserController {

    @GetMapping
    @Operation(summary = "Get all users", description = "Retrieve all users from the database")
    public List<String> getAllUsers() {
        return List.of("John", "Jane", "Alice");
    }

    @PostMapping
    @Operation(summary = "Create a new user", description = "Add a new user to the database")
    public String createUser(@RequestBody String userName) {
        return "User " + userName + " created.";
    }

    @GetMapping("/{id}")
    @Operation(summary = "Get user by ID", description = "Retrieve a user by their unique ID")
    public String getUserById(@PathVariable int id) {
        return "User " + id;
    }
}

Key Annotations

  1. @Tag: Groups related endpoints under a common heading in the Swagger UI.
  2. @Operation: Adds metadata about individual endpoints, such as a summary and description.
  3. @RequestBody and @PathVariable: Automatically documented based on their usage in the method signature.

After annotating your controllers, the Swagger UI will display detailed information about each endpoint, such as HTTP methods, descriptions, and parameters.


Customizing UI and Endpoints

Customizing Swagger UI

You can customize the Swagger UI display settings by configuring the application.yml file or application.properties.

application.yml:

springdoc:
  swagger-ui:
    path: /api-docs/ui  # Customize Swagger UI path
    display-request-duration: true  # Show request duration in the UI
    doc-expansion: full            # Expand endpoints by default
    syntax-highlighter: "monokai"  # Highlight code blocks

Customizing API Docs URL

You can change the default OpenAPI docs path (/v3/api-docs) like this:

springdoc:
  api-docs:
    path: /custom-api-docs

Adding Custom Metadata

To customize API metadata (e.g., title, description, and version), use the @OpenAPIDefinition annotation.

OpenAPIConfig.java

package com.example.demo.config;

import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.info.Contact;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.info.License;

@OpenAPIDefinition(
    info = @Info(
        title = "User Management API",
        version = "1.0.0",
        description = "API for managing users",
        contact = @Contact(name = "Support Team", email = "support@example.com"),
        license = @License(name = "Apache 2.0", url = "http://www.apache.org/licenses/LICENSE-2.0.html")
    )
)
public class OpenAPIConfig {
}

This metadata will now display in the Swagger UI header, providing helpful information to API consumers.


Securing API Docs

Protecting your API documentation is important in environments where sensitive data may be exposed. Spring Security can be used to restrict access to the Swagger UI.

Example Security Configuration

Use the following configuration to allow unauthenticated access only to Swagger endpoints while securing the rest of the application:

SecurityConfig.java

package com.example.demo.config;

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

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.csrf().disable() // Disable CSRF protection for simplicity
            .authorizeHttpRequests()
            .antMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()  // Allow public access to Swagger
            .anyRequest().authenticated();  // Protect other endpoints
        return http.build();
    }
}

Adding Basic Authentication

To add basic authentication for Swagger endpoints:

http.csrf().disable()
    .authorizeHttpRequests()
    .antMatchers("/swagger-ui/**", "/v3/api-docs/**").authenticated()
    .and()
    .httpBasic();  // Enable basic authentication

Users now need a username and password to access Swagger UI and API documentation.

Limiting Access via Profiles

You can disable Swagger in production environments by using Spring profiles:

springdoc.api-docs.enabled=false
springdoc.swagger-ui.enabled=false

Create different properties for development (application-dev.yml) and production (application-prod.yml) environments to control accessibility.


External Resources for Further Learning


Final Thoughts

Integrating Swagger/OpenAPI into a Spring Boot application significantly improves your API’s visibility and usability. By following the steps in this guide—from adding dependencies and annotating controllers to customizing the UI and securing access—you can deliver a professional, well-documented API to your application’s users.

Use this guide to streamline API documentation in your Spring Boot projects and increase productivity. Bookmark it as a reference for your future API development needs!

Similar Posts

Leave a Reply