DEV Community

Cover image for Integrating OpenAPI Documentation and Swagger UI in Spring Boot
M. Oly Mahmud
M. Oly Mahmud

Posted on

Integrating OpenAPI Documentation and Swagger UI in Spring Boot

In modern API development, OpenAPI documentation and Swagger UI are very powerful tools. It is very useful for documenting and testing the APIs. In this article, we will learn to integrate OpenAPI docs and Swagger UI into our Spring Boot 3 project.

OpenAPI

According to the official documentation,
OpenAPI Specification (formerly Swagger Specification) is an API description format for REST APIs.
An OpenAPI file allows you to describe your entire API, including:

  • Available endpoints (/users) and operations on each endpoint (GET /users, POST /users)
  • Operation parameters Input and output for each operation
  • Authentication methods
  • Contact information, license, terms of use, and other information.

This documentation is written in YAML or JSON.

Swagger

Swagger is a set of open-source tools built around the OpenAPI Specification that can help you design, build, document, and consume REST APIs.

springdoc-openapi

springdoc-openapi java library used to automate the generation of API documentation in spring boot projects. This library automatically generates API documentation in JSON/YAML and HTML format APIs.

Let's get started

We will explore how to integrate the OpenAPI documentation and Swagger UI into a Spring Boot 3 project using the springdoc-openapi.

Requirements

Before diving into the integration, ensure you have the following:

  • Java Development Kit (JDK) 17 or later
  • Spring Boot 3.x
  • Maven or Gradle
  • IDE (e.g., IntelliJ IDEA, Eclipse)

Add Dependencies

First, we need to determine the appropriate version of the springdoc-openapi-starter-webmvc-ui dependency according to the Spring Boot version. You can see the details of the version in the following link.

The compatibility matrix of springdoc-openapi with spring-boot

At this moment, I am using Spring Boot 3.4.1. So, according to the official documentation of the springdoc the version of springdoc-openapi-starter-webmvc-ui is 2.7.0.

Let's add the dependency.

Maven

Add the following dependencies to your pom.xml:

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

Gradle

If you’re using Gradle, include the dependency in your build.gradle:

implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.7.0'
Enter fullscreen mode Exit fullscreen mode

That's it. We have integrated OpenAPI Docs and Swagger UI into our Spring Boot project.

Verifying the Swagger UI and OpenAPI doc

Open a browser, and enter the following URL:
http://localhost:8080/swagger-ui/index.html

Now, you can see the Swagger UI. Here you can see the API you have built.

To verify the OpenAPI Doc, visit the following URL,
http://localhost:8080/v3/api-docs

Customizing the paths

We can customize the default path for OpenAPI doc and Swagger UI.

To customize the default endpoints, add the following code to the application.properties file.

# Custom path for the API docs
springdoc.api-docs.path=/api-docs

# Custom path for the Swagger UI
springdoc.swagger-ui.path=/swagger-ui.html
Enter fullscreen mode Exit fullscreen mode

api-docs.path: Specifies the URL path for the OpenAPI documentation.

swagger-ui.path: Sets the URL path for accessing Swagger UI.

Enhance Your Documentation (Optional)

You can enrich your API documentation with additional details using various annotations:

@Tag: Group APIs by functionality.

@Parameter: Describe query or path parameters.

@RequestBody: Document the request body format.

@ApiResponse: Document possible responses

@Schema: Describe the models

Example with Enhanced Annotations:

ProductController.java

import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;

@RestController
@RequestMapping("/api/v1/products")
@Tag(name = "Product Management", description = "Operations related to products")

public class ProductController {

    @Operation(summary = "Get product details", description = "Fetch details of a product by its ID.")
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200", description = "Product found",
            content = @Content(
                schema = @Schema(implementation = Product.class)
            )
        ),
        @ApiResponse(
            responseCode = "404", 
            description = "Product not found"
        )
    })
    @GetMapping("/{id}")
    public Product getProductById(@PathVariable Long id) {
        return new Product(id, "Sample Product", 100.0);
    }
}
Enter fullscreen mode Exit fullscreen mode

Product.java

class Product {
        private Long id;
        private String name;
        private Double price;

        // Constructor, getters, and setters omitted for brevity.
}
Enter fullscreen mode Exit fullscreen mode

Customize OpenAPI Configuration (Optional)

You can define custom metadata for your OpenAPI documentation by creating a configuration class. Here's an example:

OpenAPIConfig.java

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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenAPIConfig {

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info().title("API Title Example")
                        .description("API Description Example")
                        .version("API Version")
                        .contact(new Contact()
                                .name("API Contact Name")
                                .url("https://api.contact.url")
                                .email("example@example.email"))
                        .termsOfService("https://api.terms.of.service")
                        .license(new License()
                                .name("API License")
                                .url("https://api.license.url")))
                .externalDocs(new ExternalDocumentation()
                        .description("API External Documentation")
                        .url("https://api.external.documentation.url"));
    }
}
Enter fullscreen mode Exit fullscreen mode

This configuration adds details such as the API title, description, version, contact information, terms of service, license, and external documentation links.

Conclusion

We can see that, adding OpenAPI docs and SWagger UI is very simple. We can easily integrate this dependency to enhance our API documentation and testing.

Top comments (1)

Collapse
 
fmahadybd profile image
Mahady Hasan Fahim

Thank you for this blog post