DEV Community

Mauricio Huertas T.
Mauricio Huertas T.

Posted on

Swagger in Spring Boot 3.0

Title: How to Install Swagger in Spring Boot 3.0 with Maven

If you're working on a Spring Boot 3.0 project and want to integrate Swagger for documenting and visualizing your API, follow these simple steps.

First, add the following dependency to your pom.xml file:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.2.0</version>
</dependency>
Enter fullscreen mode Exit fullscreen mode

Then, in your application properties, include the following configuration to sort operations in the Swagger UI:

springdoc.swagger-ui.operationsSorter=method
Enter fullscreen mode Exit fullscreen mode

If you have Spring Security installed, it's crucial to allow Swagger to display. Add specific rules, for example:

return http
    .cors(c -> corsConfigurationSource())
    .csrf(csrf -> csrf.disable())
    .authorizeHttpRequests(auth -> auth
        .requestMatchers("/v3/api-docs")
        .permitAll()
        .requestMatchers("/swagger-ui/**")
        .permitAll()
        .requestMatchers("/v3/api-docs/swagger-config")
        .permitAll()
        .anyRequest()
        .authenticated());
Enter fullscreen mode Exit fullscreen mode

For more configuration, create a SwaggerConfig class with the following content:

@Bean
public OpenAPI openAPI() {
    return new OpenAPI()
            .addSecurityItem(new SecurityRequirement().addList(token))
            .components(new Components().addSecuritySchemes(tokenApp, createAPIKeyScheme()))
            .info(new Info()
                    .title("Web service API")
                    .description("API Access for applications")
                    .version("1.0.0")
                    .contact(new Contact()
                            .name("EmSolution")
                            .email("info@emsolution.com")
                            .url("www.emsolution.com"))
                    .license(new License().name("License of API")
                            .url("API license URL")));
}

private SecurityScheme createAPIKeyScheme() {
    return new SecurityScheme().type(SecurityScheme.Type.APIKEY)
            .in(SecurityScheme.In.HEADER)
            .name(tokenApp);
}
Enter fullscreen mode Exit fullscreen mode

That's it! Now you'll have Swagger integrated into your Spring Boot 3.0 project. Feel free to leave your comments and questions. Cheers!

"Finally, I appreciate your time in reading this article and hope to have your support."

Image description

Image description

Ing. Mauricio Huertas T.


Top comments (0)