Aggregating Swagger API Documentation in Spring Cloud Gateway
This article explains why and how to aggregate Swagger API documentation across multiple Spring Cloud microservices by creating a reusable swagger‑starter, configuring each service, and implementing a GatewaySwaggerResourcesProvider to expose a unified documentation entry point.
When a system consists of many microservices, accessing each service's Swagger UI separately becomes cumbersome, so a unified API documentation entry is needed.
The solution is to aggregate Swagger through the gateway, using Spring Cloud Gateway as the central point that maps to each service's /v2/api-docs endpoint.
1. Create a swagger‑starter
Define a custom starter that includes the necessary dependencies:
io.springfox
springfox-boot-starter
com.github.xiaoymin
swagger-bootstrap-uiDefine SwaggerProperties to hold API metadata and author information, and annotate it with @ConfigurationProperties and @Component so each service can configure its own values.
@Data
@ConfigurationProperties(prefix = SwaggerProperties.PREFIX)
@Component
@EnableConfigurationProperties
public class SwaggerProperties {
public static final String PREFIX = "spring.swagger";
private String basePackage;
private Author author;
private ApiInfo apiInfo;
@Data
public static class ApiInfo {
String title;
String description;
String version;
String termsOfServiceUrl;
String license;
String licenseUrl;
}
@Data
public static class Author {
private String name;
private String email;
private String url;
}
}Configure basic API info and optional OAuth2 token header in the starter.
2. Add the starter to each microservice
Include the starter as a Maven dependency:
cn.myjszl
swagger-starterThen set the Swagger properties in the service's application.yml (example shown for an order service).
After restarting, the service exposes its Swagger JSON at http://localhost:3002/swagger-order-boot/v2/api-docs .
3. Gateway aggregation
Add the same two Swagger dependencies to the gateway project and implement GatewaySwaggerResourcesProvider that implements SwaggerResourcesProvider . Its get() method collects routes, builds the URL for each service’s /v2/api-docs , and returns a list of SwaggerResource objects.
Start the gateway together with the services and open http://localhost:3001/doc.html to see the unified Swagger UI.
The article also highlights useful Swagger UI features such as search, offline Markdown export, token configuration, caching, and global parameters.
Finally, the author invites readers to follow the "码猿技术专栏" public account to obtain PDF collections of the series and encourages likes, shares, and comments.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.