Integrate OpenAPI With Spring Cloud Gateway
OpenAPI (formerly Swagger) is a standardized specification for describing RESTful APIs, enabling automated documentation, client generation, and validation. Spring Cloud Gateway is a reactive, non-blocking API gateway built on Spring WebFlux, used to route, filter, and secure microservices. Integrating OpenAPI with Spring Cloud Gateway unifies API documentation, combining gateway routes with underlying microservice APIs. This simplifies API discovery, reduces onboarding time, and ensures consistency across your microservices ecosystem.
Table of Contents#
- Introduction
- Prerequisites
- Setting Up the Project
- Understanding OpenAPI and Spring Cloud Gateway
- Integrating OpenAPI with Spring Cloud Gateway
- Example Implementation: Unified API Documentation
- Handling Multiple Microservices (API Aggregation)
- Best Practices
- Common Pitfalls and Solutions
- Advanced Configurations
- Conclusion
- References
Prerequisites#
To follow this guide, you’ll need:
- Java 11+ (Spring Cloud Gateway requires Java 11 or higher).
- Maven/Gradle for dependency management.
- Basic knowledge of Spring Boot, Spring Cloud Gateway, and OpenAPI/Swagger.
- A Spring Boot project (or create one via Spring Initializr).
Setting Up the Project#
Step 1: Add Dependencies#
For a Maven project, add these dependencies to pom.xml:
<dependencies>
<!-- Spring Cloud Gateway -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- SpringDoc for OpenAPI (WebFlux support) -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
<version>2.2.0</version>
</dependency>
</dependencies> For Gradle, add to build.gradle:
implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
implementation 'org.springdoc:springdoc-openapi-starter-webflux-ui:2.2.0' Understanding OpenAPI and Spring Cloud Gateway#
- OpenAPI (OAS) defines a language-agnostic contract for REST APIs, enabling tools like Swagger UI to generate interactive documentation, client SDKs, and validation.
- Spring Cloud Gateway acts as a reverse proxy, routing requests to microservices, applying filters (e.g., authentication, rate limiting), and handling cross-cutting concerns (e.g., CORS, error handling) in a reactive (non-blocking) manner.
Integrating OpenAPI with Spring Cloud Gateway#
Using SpringDoc for OpenAPI#
SpringDoc simplifies OpenAPI integration with Spring Boot (including reactive WebFlux apps). It auto-generates OpenAPI specs from routes, controllers, and configurations.
Configuring Routes and OpenAPI#
Step 1: Define Gateway Routes#
In application.yml, configure routes to microservices:
spring:
cloud:
gateway:
routes:
- id: user-service
uri: http://localhost:8081
predicates:
- Path=/users/** # Route requests to /users/** to user-service
- id: product-service
uri: http://localhost:8082
predicates:
- Path=/products/** # Route requests to /products/** to product-service Step 2: Configure SpringDoc#
Add SpringDoc settings to application.yml to expose OpenAPI docs and Swagger UI:
springdoc:
api-docs:
path: /api-docs # OpenAPI JSON/YAML endpoint
swagger-ui:
path: /swagger-ui.html # Swagger UI endpoint
group-configs:
- group: "gateway"
pathsToMatch: "/**" # Include all routes in the "gateway" group Example Implementation: Unified API Documentation#
Step 1: Start the Gateway and Microservices#
- The gateway runs on
http://localhost:8080. - Microservices (e.g.,
user-service,product-service) run onhttp://localhost:8081andhttp://localhost:8082, respectively.
Step 2: Access Swagger UI#
Navigate to http://localhost:8080/swagger-ui.html. SpringDoc aggregates:
- Gateway routes (e.g.,
/users/**,/products/**). - Microservices’ APIs (if they expose OpenAPI docs—see next section).
Handling Multiple Microservices (API Aggregation)#
Each microservice can expose its own OpenAPI docs (using SpringDoc). For example, in user-service:
Microservice (e.g., user-service) Configuration#
Add SpringDoc to user-service’s pom.xml/build.gradle and configure:
springdoc:
api-docs:
path: /v3/api-docs # Expose OpenAPI docs at /v3/api-docs
swagger-ui:
path: /swagger-ui.html # Optional: Expose Swagger UI for the microservice Aggregate Microservices’ Docs in Gateway#
Update the gateway’s application.yml to include microservices’ OpenAPI docs in Swagger UI:
springdoc:
swagger-ui:
urls:
- name: user-service
url: http://localhost:8081/v3/api-docs # User service’s OpenAPI docs
- name: product-service
url: http://localhost:8082/v3/api-docs # Product service’s OpenAPI docs
- name: gateway
url: /api-docs # Gateway’s own OpenAPI docs Best Practices#
- Versioning: Include API version in routes (e.g.,
/v1/users/**) and OpenAPI specs (openapi.info.version). - Security: Secure Swagger UI in production (e.g., with OAuth2, API keys) using Spring Security.
- Caching: Cache OpenAPI specs (e.g., with Redis) to reduce latency when aggregating multiple microservices.
- Error Handling: Document error responses (e.g., 404, 500) using Gateway filters.
- Gateway-Specific Endpoints: Document gateway-only endpoints (e.g.,
/actuator/health) with@Operationor similar annotations.
Common Pitfalls and Solutions#
-
CORS Issues: Configure Gateway’s CORS filter:
spring: cloud: gateway: globalcors: cors-configurations: '[/**]': allowedOrigins: "*" allowedMethods: "*" allowedHeaders: "*" -
Swagger UI Not Loading: Ensure microservices’
/v3/api-docsare reachable from the gateway. Check network connectivity and CORS. -
Incorrect Routes: Verify predicates/filters with Gateway’s debug logging:
logging: level: org.springframework.cloud.gateway: DEBUG
Advanced Configurations#
Customize Swagger UI#
Add custom CSS/JS or change layout:
springdoc:
swagger-ui:
configUrl: /custom-config.json # Point to a custom Swagger UI config
cssUrl: /custom.css # Custom CSS
jsUrl: /custom.js # Custom JS Secure OpenAPI with Spring Security#
Require authentication for Swagger UI:
@Configuration
public class SecurityConfig {
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange(exchanges -> exchanges
.pathMatchers("/swagger-ui.html", "/api-docs").authenticated()
.anyExchange().permitAll()
)
.oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::jwt);
return http.build();
}
} Conclusion#
Integrating OpenAPI with Spring Cloud Gateway unifies API documentation, simplifying discovery and consumption of microservices. By following best practices (e.g., versioning, security) and addressing common pitfalls, you can build a robust, well-documented API gateway.