Configuring Swagger 2 in your project

Let's configure Swagger 2 in your Account microservice project using Java-based configuration:

package com.dineshonjava.accountservice.config; 
 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
 
import springfox.documentation.builders.PathSelectors; 
import springfox.documentation.builders.RequestHandlerSelectors; 
import springfox.documentation.spi.DocumentationType; 
import springfox.documentation.spring.web.plugins.Docket; 
import springfox.documentation.swagger2.annotations.EnableSwagger2; 
 
@Configuration 
@EnableSwagger2 
public class SwaggerConfig {                                     
    @Bean 
    public Docket api() {  
        return new Docket(DocumentationType.SWAGGER_2)   
          .select()                                   
          .apis(RequestHandlerSelectors.any())               
          .paths(PathSelectors.any())                           
          .build();                                            
    } 
}

We have used two annotations, @Configuration and @EnableSwagger2, at the top of our configuration class; here this configuration class mainly centers on the Docket bean. The @Configuration annotation is used to make this class a configuration class for this project. The @EnableSwagger2 annotation is used to enable the Swagger 2 functionality into your project.

In the preceding configuration, we defined a bean Docket. This Docket bean of DocumentationType.SWAGGER_2 will be created by this bean definition. As you can see in the configuration code, the select() method will return an instance of ApiSelectorBuilderApiSelectorBuilder will provide a way to control the endpoints exposed by Swagger. Another method, paths(), will return an instance of a predicate. And the predicate will provide a way to select RequestHandlers. RequestHandlers can be configured by using RequestHandlerSelectors and PathSelectors.

Finally, PathSelectors's any() method will prepare documentation for your entire APIs, available through Swagger. This configuration is enough to integrate Swagger 2 into the existing Spring Boot project for the Account microservice. Let's run this project and verify that SpringFox is working.

Open the following URL in your favorite browser and see the output at

http://localhost:6060/v2/api-docs. This URL will render as JSON data of the documentation of the REST API. Let's see the following screenshot:

The result is a JSON response with a large number of key-value pairs (the screenshot displays some of the output only). This response is not very human-readable. Swagger also provides Swagger UI for the REST API documentation by adding another maven dependency in your Account microservice Spring Boot project. Let's see the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.213.212