How to Configure Swagger UI in Spring Cloud Gateway: A Step-by-Step Guide

Configuring Swagger UI in a Spring Cloud Gateway application allows you to visualize and interact with your APIs through a user-friendly interface. This guide walks you through setting up Swagger UI in your Spring Cloud Gateway application, including adding routes for API documentation and configuring the Swagger UI.

1. Add Dependencies

To get started, you need to include the necessary dependencies in your pom.xml or build.gradle. The primary dependency required is springdoc-openapi-starter-webflux-ui for integrating Swagger UI with your Spring Cloud Gateway.

For Maven (pom.xml):

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
    <version>2.0.5</version>
</dependency>

For Gradle (build.gradle):

implementation 'org.springdoc:springdoc-openapi-starter-webflux-ui:2.0.5'

2. Update Application Configuration

Configure your application.yml (or application.properties) to set up routing and Swagger UI options. You need to define routes for your services and configure Swagger UI to correctly display documentation for these services.

application.yml Configuration:

spring:
  application:
    name: apigw
  cloud:
    gateway:
      routes:
        - id: user
          uri: lb://USER-SERVICE
          predicates: 
            - Path=/users/v3/api-docs, /api/v1/users/** # Define routes for Swagger API documentation
        # Add more routes for other services as needed

server:
  port: 8080

springdoc:
  enable-native-support: true
  api-docs:
    enabled: true
  swagger-ui:
    enabled: true
    path: /swagger-ui.html
    config-url: /v3/api-docs/swagger-config
    urls:
      - url: /v3/api-docs
        name: API Gateway Service
      - url: /users/v3/api-docs
        name: User Service
      # Add more URLs for other services as needed

In this configuration:

  • Routes: Define how Spring Cloud Gateway routes requests to various services. The Path predicate is used to match paths for Swagger API documentation.

  • Swagger UI: Configured to be accessible at /swagger-ui.html and fetches API documentation from /v3/api-docs.

3. Serve Swagger UI

With the dependencies and configuration in place, Swagger UI should now be available at: http://localhost:8080/webjars/swagger-ui/index.html

This URL provides a visual interface where you can interact with the APIs documented through Swagger.