Logo

dev-resources.site

for different kinds of informations.

Integrating OpenAPI Documentation and Swagger UI in Spring Boot

Published at
12/20/2024
Categories
java
springboot
openapi
documentation
Author
olymahmud
Author
9 person written this
olymahmud
open
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("[email protected]"))
                        .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.

openapi Article's
30 articles in total
Favicon
How to Optimize Large JSON Files for Use with ChatGPT API?
Favicon
SpringBoot Web Service - Part 5 - Github Action
Favicon
SpringBoot Web Service - Part 2 - Preparing Using Spring Initializr
Favicon
SpringBoot Web Service - Part 1 - Create Repository
Favicon
SpringBoot Web Service - Part 4 - Initial Configuration
Favicon
Swagger
Favicon
How I write Go APIs in 2025 - my experience with Fuego
Favicon
Building and Deploying a New API (Part 1)
Favicon
.NET 9 Revolutionizing documentation of APIs : From Swashbuckle to Scalar πŸš€
Favicon
Parameter Position in OpenAPI
Favicon
Why Clear and Meaningful Status Codes Matter in Your REST API
Favicon
.NET 9 Improvements for ASP.NET Core: Open API, Performance, and Tooling
Favicon
Integrating OpenAPI Documentation and Swagger UI in Spring Boot
Favicon
How Scale Changes Everything - The LiveAPI Perspective
Favicon
A Closer Look At API Docs Generated via LiveAPI's AI
Favicon
Musings Over What Makes LiveAPI Different (from Swagger Et Cetera)
Favicon
An Online Free API AutoTesting Tool That Completes 160 Hours of Testing Work for 20 APIs in Just 3 Minutes
Favicon
How to Improve Development Efficiency Through Automated API Testing
Favicon
New to dev.to and Excited to Share ProxyConf: My Elixir-Powered API Control Plane
Favicon
Exploring AutoAPI: An Automation Tool to Simplify Frontend Development
Favicon
OpenAPI and Frontend
Favicon
How to Generate and Display Swagger (OpenAPI) Documentation for Your Laravel API
Favicon
Why we chose the Go Huma framework to develop our API endpoints
Favicon
New Swagger-UI embedding Cloud TypeScript Editor with RPC SDK
Favicon
Laravel API Documentation Made Easy: Step-by-Step Swagger Integration
Favicon
Open API specs with more than one YAML file
Favicon
Introducing Swama: A CLI Tool for Swagger/OpenAPI Interactions
Favicon
Swagger UI + Docker: Initial Setup
Favicon
Merge and bundle open api yaml files for swagger
Favicon
Tutorial: Build a Java SDK based on OpenAPI Spec

Featured ones: