Customizing Swagger UI and API Metadata

Swagger UI is a powerful tool that provides an interactive and user-friendly interface for exploring and testing RESTful APIs. It automatically generates documentation based on the metadata provided by the API. In this article, we will explore how to customize Swagger UI and API metadata in a Spring Boot application.

Adding Swagger UI and Dependencies

To get started, we need to add the necessary dependencies to our Spring Boot project. In the pom.xml file, add the following dependencies:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.5.2</version>
</dependency>
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-data-rest</artifactId>
    <version>1.5.2</version>
</dependency>

These dependencies include springdoc-openapi-ui which provides the Swagger UI, and springdoc-openapi-data-rest which enables integration with Spring Data REST.

Enabling Swagger UI

To enable Swagger UI in our application, we need to add a few configuration options. Create a new class named SwaggerConfig and annotate it with @Configuration:

@Configuration
public class SwaggerConfig {
    // Configuration code here
}

Now, let's add the necessary beans to enable Swagger UI and API metadata:

@Configuration
public class SwaggerConfig {
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info().title("My API").version("1.0.0"))
                .addServersItem(new Server().url("http://localhost:8080"));
    }
}

In this code snippet, we are creating a new instance of OpenAPI and customizing it by setting the API title, version, and server URL. Feel free to customize these values according to your project.

Customizing Swagger UI

Swagger UI can be customized in various ways to align with your project's branding and requirements. To change the default colors, fonts, and other visual aspects of Swagger UI, we can leverage CSS customization.

Create a new CSS file named swagger-ui-custom.css and place it in the src/main/resources/static directory. Here is an example of how you can customize the colors of Swagger UI:

/* swagger-ui-custom.css */

.swagger-ui .opblock .opblock-summary .opblock-summary-path,
.swagger-ui .opblock .opblock-summary .opblock-summary-method {
    color: #337ab7;
}

In this example, we changed the color of the API paths and HTTP methods to the Bootstrap primary color (#337ab7).

To apply this custom CSS file to Swagger UI, we need to configure the location of the CSS file in our SwaggerConfig class:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    // ...

    @Value("classpath:static/swagger-ui-custom.css")
    Resource cssResource;

    @Bean
    public OpenApiCustomiser swaggerCustomiser() {
        return openApi -> {
            openApi.getExtensions().add(
                    new Extension().name("custom-css").value(
                            "{ \"url\":\"/swagger-ui-custom.css\" }"
                    )
            );
        };
    }
}

The swaggerCustomiser bean customizes the generated OpenAPI instance by adding an extension to point to our custom CSS file. The openApi.getExtensions().add(...) code snippet sets the url property to the location of the CSS file.

Customizing API Metadata

Swagger UI generates API metadata by scanning the project's code and extracting information from annotated classes and methods. To customize the API metadata, we can add custom annotations and attributes to our code.

For example, let's say we want to provide additional information and descriptions for our REST controllers and API endpoints. We can achieve this by adding annotations and attributes from the Swagger API, such as @Api and @ApiOperation.

@RestController
@Api(tags = "User API")
public class UserController {

    @ApiOperation(value = "Get user by ID")
    @GetMapping("/users/{id}")
    public User getUserById(@PathVariable Long id) {
        // ...
    }
}

In this code snippet, we annotated the UserController class with @Api to provide a tag for the Swagger UI documentation. We also annotated the getUserById method with @ApiOperation to specify a custom value for the API operation.

Conclusion

Swagger UI provides an excellent way to document and explore RESTful APIs. By customizing Swagger UI and API metadata, we can enhance the user experience and align the documentation with our project's branding and requirements. In this article, we learned how to enable Swagger UI in a Spring Boot application, customize its visual aspects with CSS, and modify the API metadata using Swagger annotations.


noob to master © copyleft