Integrating Swagger with Spring Boot Applications

Explore practical examples of integrating Swagger into Spring Boot applications for enhanced API documentation.
By Jamie

Integrating Swagger with Spring Boot Applications

Swagger is a powerful tool for documenting RESTful APIs. By integrating Swagger with Spring Boot, developers can create interactive API documentation that simplifies the development and testing process. Below are three diverse examples demonstrating how to effectively implement Swagger in Spring Boot applications.

Example 1: Basic Swagger Setup in a Spring Boot Application

Use Case

This example demonstrates the basic setup of Swagger in a Spring Boot application to document a simple REST API.

To start, ensure you have the following dependencies in your pom.xml:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

Then, create a configuration class to enable Swagger:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                .paths(PathSelectors.any())
                .build();
    }
}

After setting this up, you can run your Spring Boot application and access the Swagger UI at http://localhost:8080/swagger-ui.html. This will provide a user-friendly interface to explore your API endpoints.

Notes

  • Ensure the base package in RequestHandlerSelectors matches the package where your controllers are located.
  • You can customize the Docket bean further to include descriptions, versioning, and more.

Example 2: Documenting API Endpoints with Annotations

Use Case

In this example, we will enhance our API documentation by using Swagger annotations to provide more details about the API endpoints.

First, ensure you have the same dependencies as the previous example. Then, create a simple REST controller:

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Api(value = "User Management System")
public class UserController {
    @GetMapping("/users")
    @ApiOperation(value = "Get a list of users", response = User[].class)
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successfully retrieved list"),
        @ApiResponse(code = 404, message = "Users not found")
    })
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }
}

In this controller, we have annotated the getAllUsers method with @ApiOperation and @ApiResponses to provide detailed descriptions and responses.

Notes

  • You can find more Swagger annotations to document request parameters, response models, and more in the Swagger annotations documentation.
  • This approach helps in generating comprehensive API documentation that is useful for both developers and end-users.

Example 3: Using Swagger with Spring Security

Use Case

This example demonstrates how to integrate Swagger with a Spring Boot application that has Spring Security enabled, allowing for secured API documentation access.

First, include the necessary dependencies in your pom.xml, as in previous examples. Next, configure Spring Security to permit access to the Swagger endpoints:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/v2/api-docs", "/swagger-resources/**", "/swagger-ui.html").permitAll()
            .anyRequest().authenticated();
    }
}

This configuration allows unrestricted access to Swagger-related endpoints while requiring authentication for all other requests. You can then test the API documentation by accessing http://localhost:8080/swagger-ui.html without authentication.

Notes

  • Adjust the security configurations based on your application’s needs and security policies.
  • Ensure that you have a proper authentication mechanism in place for your application, as this example is for demonstration purposes only.

By following these examples of integrating Swagger with Spring Boot applications, you can create comprehensive, interactive API documentation that enhances the developer experience and improves the usability of your APIs.