Implementing springdoc-openapi swagger ui in Spring Boot application

Implementing springdoc-openapi swagger ui in Spring Boot application

Adding springdoc-openapi swagger ui in a Spring Boot application

Using springdoc-openapi Swagger in Spring Boot is clearer and easier to use due to its auto-configuration mechanism. In this tutorial, we are learning how to set up the swagger ui in the application and customize the default configuration.

Introduction

Introduction to Swagger

Swagger is an open-source framework that is used to document, design, build, and utilize RESTful web services. It uses the open api specification(OAS) that describes the REST API in a machine-readable format. In brief, it will help to test the application endpoints.
When we open the swagger ui url in the browser, we will see the documentation page that lists all the endpoints, request parameters, and request and response formats, which allows to test them directly from the interface.

Springdoc OpenAPI Dependency

The springdoc-openapi-starter-webmvc-ui is the modern library that automates the generation of api documentations in a Spring project.
When we add the dependency to the build file, it will automatically scan the application at startup, find all the REST controllers, and generate api documentation based on the REST annotations and method signatures.

Adding Dependency

First, let's add the springdoc-openapi-starter-webmvc-ui to our project.

For Maven

Inside pom.xml file
java
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.8.17</version> 
</dependency>

For Gradle

Inside build.gradle file
java
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.17'
Refer to the latest version from the release.
Click Sync and Reload for the dependency to download.

Accessing the Swagger UI

While running the spring-boot application with the dependency setup, you might see the Spring app output as below.
bash
SpringDoc /v3/api-docs endpoint is enabled by default. To disable it in production, set the property 'springdoc.api-docs.enabled=false'
SpringDoc /swagger-ui.html endpoint is enabled by default. To disable it in production, set the property 'springdoc.swagger-ui.enabled=false'
This shows that it will configure all the default endpoints and necessary configurations by default with the Spring Boot auto-configuration mechanism.
Let's open the endpoints.
For http://localhost:8080/v3/api-docs you can see the JSON output.
bash
{
openapi: "3.1.0",
info: {
title: "OpenAPI definition",
version: "v0"
},
servers: [
{
url: "http://localhost:8080",
description: "Generated server url"
}
],
paths: {
/product/{productId}: {
get: {
tags: [
For http://localhost:8080/swagger-ui/index.html you can see the interactive ui for testing the endpoints.
Article Image
This is the default configuration setup ui interactive page.

Adding OpenAPI Configuration

Now, let's customize the default configuration using a configuration file.
Create OpenApiConfig.java
java
package com.csbyte.product.config;

import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenApiConfig {

    @Value("${api.common.licenseUrl:https://www.apache.org/licenses/LICENSE-2.0}")
    String apiLicenseUrl;

    @Value("${api.common.contact.name:CsByte Support}")
    String apiContactName;

    @Value("${api.common.description:CsByte API documentation for Product service.}")
    String apiDescription;

    @Value("${api.common.contact.url:https://csbyte.com/support}")
    String apiContactUrl;

    @Value("${api.common.externalDocDesc:Detailed System Architecture Documentation}")
    String apiExternalDocDesc;

    @Value("${api.common.termsOfService:https://csbyte.com/terms}")
    String apiTermsOfService;

    @Value("${api.common.version:1.0.0}")
    String apiVersion;

    @Value("${api.common.externalDocUrl:https://csbyte.com/docs}")
    String apiExternalDocUrl;

    @Value("${api.common.title:CsByte Product API}")
    String apiTitle;

    @Value("${api.common.contact.email:[email protected]}")
    String apiContactEmail;

    @Value("${api.common.license:Apache 2.0}")
    String apiLicense;

    @Bean
    public OpenAPI getOpenApiDocumentation() {
        return new OpenAPI()
                .info(new Info().title(apiTitle)
                        .version(apiVersion)
                        .description(apiDescription)
                        .contact(new Contact()
                                .name(apiContactName)
                                .url(apiContactUrl)
                                .email(apiContactEmail))
                        .termsOfService(apiTermsOfService)
                        .license(new License()
                                .name(apiLicense)
                                .url(apiLicenseUrl)))
                .externalDocs(new ExternalDocumentation()
                        .description(apiExternalDocDesc)
                        .url(apiExternalDocUrl));
    }
}
This is the sample configuration file for customizing the default properties, which provide general descriptive information about the API. You can set these config properties inside the application.yml or application.properties file.

Configure spring-doc Open Api

We can configure the springdoc configuration inside application.yml file as
bash
springdoc:
  swagger-ui.path: /openapi/swagger-ui.html
  api-docs.path: /openapi/api-docs
  packagesToScan: com.csbyte.product
  pathsToMatch: /**
Now, this will change the api docs URLs to http://localhost:8080/openapi/swagger-ui/index.html and http://localhost:8080/openapi/api-docs . We can set the package for api documentation and paths to match.

Adding API Documentation

Let's look into the sample endpoint for the product service.
java
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Tag(name = "Product", description = "REST API for product.")
public interface ProductService {

    @Operation(
            summary = "Get product from product id",
            description = "Product description")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "OK"),
            @ApiResponse(responseCode = "404", description = "Not found"),
    })
    @RequestMapping(
            value = "/product/{productId}",
            produces = "application/json"
    )
    Product getProduct(@PathVariable int productId);
}
  • @Tag is used to describe entire class endpoints
  • @Operation is used for the specific endpoint that uses it
  • @ApiResponses is used to define the possible HTTP responses that the endpoint will return. In our case 200 and 404 responses
Note: we can use the property placeholder for each text and provide the values via the application.yml file.
Article Image
All the changes are highlighted in the given image.
Now you can add the same for different endpoints and test. Make sure to disable the setup in production by adding the following property in application.properties or application.yml file.
bash
springdoc.swagger-ui.enabled=false

Setup for Spring WebFlux

We can use the springdoc-openapi for the reactive application. Add the following configuration for WebFlux.

For Maven

java
  <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-starter-webflux-api</artifactId>
      <version>2.8.17</version>
   </dependency>

For Gradle

java
implementation 'org.springdoc:springdoc-openapi-starter-webflux-api:2.8.17'
We finally configure the spring open api docs setup for our application by utilizing the defualt swagger config, and later we customize it. Implement in our application with custom endpoint descriptions and also add the dependencies for a Spring WebFlux application.
If you want to learn more about OpenApi Swagger implementation in detail, follow the guide.