How to Configure Swagger 3 in a Spring Boot Application with Springfox
Published: 2024-05-18 04:25:09


## Introduction

Swagger, now part of the OpenAPI initiative, is a powerful tool for documenting and testing RESTful APIs. Using Springfox, you can easily integrate Swagger 3 (OpenAPI 3) with your Spring Boot application. In this article, I’ll guide you through the steps to set up and configure Swagger 3 using Springfox.

## Prerequisites

- Basic knowledge of Spring Boot
- Java 8 or higher
- Maven for dependency management

## Step 1: Add Springfox Dependency

First, add the necessary Springfox dependency to your `pom.xml` file.

```xml
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
```

## Step 2: Configure Swagger

Create a configuration class to set up Swagger with Springfox. This is where you can customize various aspects of your API documentation.

```java
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.yourpackage"))
                .paths(PathSelectors.any())
                .build();
    }
}
```

In this configuration:

- `@EnableSwagger2`: Enables Swagger 2 documentation.
- `Docket`: Configures the Swagger 2 documentation with the base package for your controllers and paths to include.

## Step 3: Annotate Your Controllers

Use annotations to document your endpoints. Springfox will automatically detect these annotations and include them in the generated documentation.

```java
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1/auth")
@Api(tags = "Authentication API", description = "API for user authentication")
public class AuthController {

    @GetMapping("/hello")
    @ApiOperation(value = "Hello World", notes = "Returns a greeting message")
    public String hello() {
        return "Hello, World!";
    }
}
```

In this example:

- `@Api`: Defines a tag and description for the controller.
- `@ApiOperation`: Provides metadata about the operation, including a value and notes.

## Step 4: Configure Security for Swagger Endpoints

If you need to allow specific URLs to be accessed without authentication, configure your Spring Security settings accordingly.

```java
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 SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/api/v1/auth/**",
                         "/v3/api-docs",
                         "/v2/api-docs",
                         "/swagger-resources/**",
                         "/swagger-ui/**",
                         "/webjars/**").permitAll()
            .anyRequest().authenticated();
    }
}
```

## Step 5: Access Swagger UI

After setting up and running your Spring Boot application, you can access the Swagger UI to view and test your API documentation.

1. Start your Spring Boot application.
2. Open your browser and navigate to `http://localhost:8080/swagger-ui/`.

You should see the Swagger UI with your documented API endpoints.

## Conclusion

Integrating Swagger 3 with your Spring Boot application using Springfox is straightforward and immensely beneficial for documenting and testing your APIs. By following these steps, you can set up comprehensive and interactive API documentation that will make development and collaboration much easier.

---
You can connect with me on LinkedIn : [Indranil Dutta](https://www.linkedin.com/in/toindranildutta)

I hope this guide helps you set up Swagger 3 in your Spring Boot application using Springfox. If you have anything to share more, please comment below.