Use of interface tools Swagger2 and Swagger-UI

Table of contents

1. Why do we need interface visualization tools?

2. Introduction to Swagger-UI:

1. Import the dependencies of swagger2 in the project's pom file

2. Download the Swagger-UI project

3. Introduce Swagger-UI

4. Write configuration files

The first:

The second type:

5. Visit the api documentation page

6. If the access fails, proceed to step six. If the access is successful, no operation is required.


1. Why do we need interface visualization tools?

Our projects often involve a large number of interfaces and complex functionality. When developers call the API in the service or testers perform testing, they need to know the functions provided by the service and how to obtain the API of the service. Commonly used interface tools include: swagger, postman, SoapUI, cURL, Fiddler, etc. Here's how to use swagger.

2. Introduction to Swagger-UI:

        ​​​Swagger-UI is a very useful tool that allows anyone to interact with the backend server API interface methods in a visual way without implementing any logic.

        The configuration of Swagger-UI can exist independently and will not affect other business codes. By introducing the configuration of Swagger-UI, users can automatically generate corresponding visual interface documents and test the interfaces in the project. This greatly simplifies the access process between the client and the server, making it easier for developers and testers to use.

1. Import the dependencies of swagger2 in the project's pom file

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

2. Download the Swagger-UI project

https://github.com/swagger-api/swagger-ui.git

Go to the above GitHub address and download it locally in the form of a compressed package, and then decompress it to obtain it; you can also install the git management tool locally and directly pull it to the local through the git clone command.

3. Introduce Swagger-UI

        Find the Swagger-UI project you just downloaded, enter the project and find the dist directory, and copy the entire dist directory to the resources directory of the Swagger-UI tool project. The files in the dist directory are mainly css, js, html and other files, which are used to display and render the Swagger-UI tool page.

4. Write configuration files

        Create the Swagger2Config.java configuration file in the config directory and write API-related configuration information. There are many ways to write the content of this configuration file, but the functions are the same. Here are 2 types, you can choose according to your preference.

The first:

public class Swagger2Config implements WebMvcConfigurer {
    /**
     * 创建 API 应用
     * apiInfo 增加 API 相关信息
     * 通过 select() 函数返回一个 ApiSelectorBuilder 实例,用来控制哪些接口暴露给 Swagger 来展现
     * 本例采用指定扫描的包路径来定义指定要建立 API 的目录
     */
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo()) // 用来展示该 API 的基本信息
                .select()   // 返回一个 ApiSelectorBuilder 实例,用来控制哪些接口暴露给 Swagger 来展现
                .apis(RequestHandlerSelectors.basePackage("com/six/campuseventmanagementsystem/controller"))   // 配置包扫描路径(根据自己项目调整,通常配置为控制器路径)
                .paths(PathSelectors.any()) //
                .build();
    }

    /**
     * 创建 API 的基本信息(这些基本信息会展现在文档页面中)
     * 访问地址:http://xxx/swagger-ui.html
     */
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("校园赛事活动管理系统")
                .description("校园赛事活动管理系统 API接口文档")
                .termsOfServiceUrl("http://localhost:8080/")
                .contact(new Contact("ambrose", "swagger.example", "[email protected]"))
                .version("3.0")
                .build();
    }
}

The second type:

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
	//定义API接口映射路径	
    public static final String DEFAULT_INCLUDE_PATTERN = "/user/.*";
    private final Logger log = 
    		LoggerFactory.getLogger(SwaggerConfiguration.class);
    @Bean
    public Docket swaggerSpringfoxDocket() {
      log.debug("Starting Swagger");
      StopWatch watch = new StopWatch();
      watch.start();
      //用于生成对应API接口文档的描述信息,可省略
      ApiInfo apiInfo = new ApiInfo("用户管理API接口测试文档","description",
        		"termsOfServiceUrl","contact","version","","");
      Docket docket = new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo)
        .genericModelSubstitutes(ResponseEntity.class)
        .forCodeGeneration(true)
        .genericModelSubstitutes(ResponseEntity.class)
        .directModelSubstitute(java.time.LocalDate.class, String.class)
        .directModelSubstitute(java.time.ZonedDateTime.class, Date.class)
        .directModelSubstitute(java.time.LocalDateTime.class, Date.class)
        .select()                
        .paths(regex(DEFAULT_INCLUDE_PATTERN))//匹配路径生成对应接口文档 
        .build();
      watch.stop();
      log.debug("Started Swagger in {} ms", watch.getTotalTimeMillis());
      return docket;
    }
}

5. Visit the api documentation page

        Run the project and enter the page through the request path corresponding to "service address IP+port+/swagger-ui.html". The path is generally http://localhost:8080/swagger-ui.html

6. If the access fails, proceed to step six. If the access is successful, no operation is required.

If the access fails, the reason may be that the swagger-ui file cannot be accessed. You only need to add a configuration file WebMvcConfig, reimplement the WebMvcConfigurer class and respecify the path.

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 解决静态资源⽆法访问
//        registry.addResourceHandler("/**")
//                .addResourceLocations("classpath:/static/");
        // 解决swagger⽆法访问
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        // 解决swagger的js⽂件⽆法访问
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

Guess you like

Origin blog.csdn.net/weixin_51451545/article/details/131267498