Centralized Swagger documentation with Spring Cloud Gateway

Hi folks!
API documentation is an essential part of modern software development, as it allows developers to understand the functionality and behavior of an API. One popular tool for generating API documentation is Swagger, which provides a user-friendly interface for interacting with APIs and generating documentation automatically. In a microservice architecture, it can be challenging to manage the documentation for multiple APIs, as each service may have its own Swagger documentation. In this article, we will explore how to centralize the Swagger documentation for a set of microservices using Spring Cloud Gateway.
Spring Cloud Gateway is a lightweight, reactive API gateway built on top of the Spring Framework. It can be used to route HTTP requests to microservices and provide additional features such as load balancing, rate limiting, and security. One useful feature of Spring Cloud Gateway is its ability to aggregate Swagger documentation from multiple microservices.
Centralized Swagger with Spring Cloud Gateway:
On Spring Cloud Gateway add these dependencies:
implementation('org.springdoc:springdoc-openapi-starter-webflux-ui:2.0.2')
implementation('org.springdoc:springdoc-openapi-starter-webflux-api:2.0.2')
On application.yml add this configuration:
spring:
cloud:
gateway:
routes:
- id: openapi
uri: http://localhost:${server.port}
predicates:
- Path=/v3/api-docs/**
filters:
- RewritePath=/v3/api-docs/(?<path>.*), /$\{path}/v3/api-docs
- id: service-1
uri: lb://service-1
predicates:
- Path=/service-1/**
filters:
- RewritePath=/service-1/(?<path>.*), /$\{path}
- id: service-2
uri: lb://service-2
predicates:
- Path=/service-2/**
filters:
- RewritePath=/service-2/(?<path>.*), /$\{path}
springdoc:
enable-native-support: true
api-docs:
groups:
enabled: true
enabled: true
group-configs:
- group: service-1
paths-to-match:
- /service-1/**
display-name: Service 1
- group: service-2
paths-to-match:
- /service-2/**
display-name: Service 2
swagger-ui:
config-url: /v3/api-docs/swagger-config
url: /v3/api-docs
urls:
- url: /service-1/v3/api-docs
name: Service 1
- url: /service-2/v3/api-docs
name: Service 2
That’s it!
Enjoy your new centralized Swagger documentation!
Written with the help of ChatGPT