Centralized API Documentation in microservice using SpringBoot, SpringFox Swagger-UI and Eureka

Tram Ho

The article shows how to easily document multiple Spring-based REST applications using the SpringFox Swagger-UI library in a microservices environment.

1. Problem

As you know, it is very easy to document a Spring REST Service application using the SpringFox Swagger-UI library, but there is a problem that arises when working in an environment where we have a lot of REST application that is typically a microservices environment. Most of us manage a separate Swagger-UI for each service, which means that each service will need a separate endpoint to access Swagger-UI and we have to have different URLs for different services. .

2. Solution

To be able to access all API documents from a single URL we can implement the following solution:

  1. Retrieve all registered services list from service registry, here is Eureka server
  2. For each registered service, pull Swagger Definition JSON to a centralized API document service and store it locally. Specifically here will use Concurrent Map to save JSON in local memory
  3. Refresh in-memory context periodically to automatically update the JSON definition when services are added, updated, or removed from the service registry
  4. Provide a single endpoint to access the centralized API document service, where all the API documents of the entire service in the system are centralized.

singleswagger.png

3. Implementation

For example, we have a system of microservices consisting of 2 main services, Person Service and Employee Service. Now let’s implement a document service to centralize all API documents from Person Service and Employee Service. The service model will look like this: solution.png

  1. central-docs-eureka-server: Service registry provided by Netflix Eureka
  2. employee-service and person-service: 2 main REST services have integrated Swagger-UI
  3. documentation-service: service collects all API documents from other services and provides Document UI with a single endpoint

final.png

3.1 SwaggerUIConfiguration

Spring configuration class registers instance of SwaggerResourcesProvider, this class reads swagger-api JSON files from ServiceDefinitionsContext

3.2 ServiceDefinitionController

Adds API that returns JSON definition information by service id from ServiceDefinitionsContext

3.3 ServiceDefinitionsContext

Component stores all JSON definitions in memory

3.4 ServiceDescriptionUpdater

This is the most important component, this component is responsible for pulling all the JSON definitions from the services registered on the service registry and storing them in the ServiceDefinitionsContext.

4. Summary

All source code in the article can be found on Github

Share the news now

Source : Viblo