Introduction

Adding Swagger to a Spring Boot application enhances its usability by providing a user interface to interact with RESTful APIs. Swagger streamlines API documentation and enables developers and testers to invoke web API endpoints easily. This guideline covers the steps to integrate Swagger into a Spring Boot project, describing different approaches with sample Kotlin code snippets.

Solution

Using Springfox

Springfox is a popular library that integrates seamlessly with Spring Boot to automatically generate OpenAPI (Swagger) documentation. Although Springfox has some limitations, particularly with newer versions of Spring Boot (2.6 and later), it remains a useful tool for legacy and certain projects.

Advantages:

  • Ease of use: Requires minimal configuration to get started.
  • Annotations: Provides annotations to document endpoints directly in the controller code.

Disadvantages:

  • Compatibility issues: Does not work with Spring Boot 2.6 and newer versions.
  • Maintenance: Slower development and update cycle.

Dependencies

Add the following dependencies to your build.gradle.kts file:

dependencies {
    implementation("io.springfox:springfox-boot-starter:3.0.0")
}

Configuration

Create a configuration class for Springfox:

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

@Configuration
class SwaggerConfig {
    @Bean
    fun api(): Docket {
        return Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.yourpackage"))
            .paths(PathSelectors.regex("/api/.*"))
            .build()
    }
}

Output

Access the Swagger UI at http://localhost:8080/swagger-ui/. This user interface allows you to interact with the API endpoints defined in your application.

{
  "swagger": "2.0",
  "info": {
    "description": "API documentation for Spring Boot application",
    "version": "1.0.0",
    "title": "API Documentation"
  },
  "host": "localhost:8080",
  "basePath": "/api",
  ...
}

Using Springdoc

Springdoc is a newer library that provides a more updated and robust integration with Spring Boot applications and supports OpenAPI 3.0 specifications.

Advantages:

  • Robustness: Better support for the latest Spring Boot versions.
  • Maintenance: Frequently updated with a faster release cycle.
  • OpenAPI 3.0: Fully supports OpenAPI 3.0 features.

Disadvantages:

  • Learning curve: Slightly more complex to set up initially compared to Springfox.

Dependencies

Add the following dependencies to your build.gradle.kts file:

dependencies {
    implementation("org.springdoc:springdoc-openapi-ui:1.5.9")
}

Configuration

Create a configuration class for Springdoc:

import io.swagger.v3.oas.models.OpenAPI
import io.swagger.v3.oas.models.info.Info
import org.springdoc.core.GroupedOpenApi
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

@Configuration
class SwaggerConfig {
    @Bean
    fun customOpenAPI(): OpenAPI {
        return OpenAPI().info(
            Info()
                .title("Spring Boot REST API")
                .version("1.0.0")
                .description("API documentation for Spring Boot application")
        )
    }

    @Bean
    fun api(): GroupedOpenApi {
        return GroupedOpenApi.builder()
            .group("public-api")
            .pathsToMatch("/api/**")
            .build()
    }
}

Output

Access the Swagger UI at http://localhost:8080/swagger-ui.html. This user interface allows you to interact with OpenAPI 3.0 documented endpoints.

{
  "openapi": "3.0.1",
  "info": {
    "title": "Spring Boot REST API",
    "version": "1.0.0",
    "description": "API documentation for Spring Boot application"
  },
  "servers": [
    {
      "url": "http://localhost:8080",
      "description": "Local server"
    }
  ],
  ...
}

Example Controller with Annotations

Using Springdoc, add annotations to a REST controller to enable detailed documentation:

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

@RestController
@RequestMapping("/api")
@Tag(name = "Example Controller", description = "Controller for example API endpoints")
class ExampleController {
    @GetMapping("/hello")
    @Operation(summary = "Get Hello Message", description = "Returns a simple hello message.")
    fun getHello(): String {
        return "Hello, World!"
    }
}

Access the endpoint documentation and testing interface using the UI link provided.

Similar Topics

Here are some similar topics that might be of interest:

  1. How to configure CORS in Spring Boot
  2. How to secure REST endpoints using Spring Security
  3. How to set up Spring Boot with JPA and Hibernate
  4. How to create a custom error handling in Spring Boot
  5. How to document API with OpenAPI 3.0
  6. How to set up pagination and sorting in Spring Boot
  7. How to integrate Spring Boot with Kubernetes
  8. How to use WebFlux for reactive programming in Spring Boot
  9. How to create a multi-module Spring Boot project
  10. How to configure logging in Spring Boot
  11. How to use Thymeleaf with Spring Boot
  12. How to perform unit testing in Spring Boot
  13. How to deploy Spring Boot application to AWS
  14. How to implement OAuth2 authentication in Spring Boot
  15. How to use Docker with Spring Boot
  16. How to handle exceptions globally in Spring Boot
  17. How to use Redis with Spring Boot
  18. How to migrate a legacy application to Spring Boot
  19. How to use RabbitMQ with Spring Boot
  20. How to create scheduled tasks in Spring Boot