API Gateway — Swagger Composition

Deniz G
2 min readOct 14, 2021

OpenAPI provides a specification for creating informative, readable, easy-to-follow Rest API documentation. On the Spring side, there are Springfox and Springdoc implementations for this. API documentation is automatically generated from the code by using these libraries in the application startup. Swagger provides an user interface using this information. Springfox doesn’t have reactive support for now, but Springdoc provides it.

Swagger composition is to combine the API information of microservices on the API gateway and present it from a single point. The only job the gateway will do is to combine and display the documents created in the microservices within itself.

Let’s show this over Spring Cloud Gateway. Assume that we offer lots of microservices through API Gateway. Let one of these services use Springfox and its name is profile.

We can visit Springfox documentation through http://profile-address/v2/api-docs. We can also visit Swagger UI through http://profile-address/swagger-ui.html.

profile swagger ui by springfox (/swagger-ui.html)

The definition of profile microservice in Spring Cloud Gateway is as follows

- id: profile_route  
- Path=/profile/**
- RewritePath=/profile/(?<segment>.*), /$\{segment}
- RemoveRequestHeader=Cookie
uri: ${kubernetes-services.profile}

Spring Cloud Gateway has to use Springdoc for Rest API documentation because Springfox doesn’t have reactive support at the moment. We will take the route definitions defined in the gateway and introduce it to Springdoc.

swagger composition

Now, we can access the Rest API documentation of each route defined through the gateway. Springdoc takes route name and if it matches with _route postfix, it will remove postfix, create a new group and compose it to Springdoc documentation.

For example, profile_route is now accessible through http://gateway-address/v3/api-docs/profile.

But, there is no such a endpoint in gateway server. So, we should redirect the requests
From http://gateway-address/v3/api-docs/profile
To http://gateway-address/profile/v2/api-docs

- id: swagger
- Path=/v3/api-docs/**
- RewritePath=/v3/api-docs/(?<path>.*), /$\{path}/v2/api-docs
uri: http://localhost:${server.port}

So, redirected request will be matched by profile_route definition, and it will be redirected to profile microservice again.
From http://gateway-address/profile/v2/api-docs
To http://profile-address/v2/api-docs

gateway swagger ui by springdoc (/webjars/swagger-ui/index.html)

In the same way, you can perform Rest operations on desired microservice by selecting from the dropdown menu at the top right.