Take a quick look at Swagger

Posted by mikesheridan5 on Mon, 11 May 2020 19:42:36 +0200

1, Swagger

1. What is Swagger?

Swagger is a standardized and complete framework for generating, describing, invoking, and visualizing Restful style Web services.
Simple understanding: it is a REST API document generation tool, which can generate online interface documents and facilitate interface testing.

2. Why Swagger?

When front-end and back-end are separated for development, an interface document needs to be provided for the convenience of front-end and back-end interface call specifications. However, maintaining this interface document is a very cumbersome task, which may cause the front-end and back-end interface call to fail due to careless forgetting to update the document.
Swagger is to solve this problem (online interface document). It defines annotation on the interface method and forms an html page according to the annotation. Every time the interface is modified, the html page will change accordingly, thus ensuring the correctness of the interface document. Through the html page, you can easily and clearly know the function of this interface and test it.

3. Spring boot integrates Swagger?

(1)Step1:
Import dependent jar packages.

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

 

(2)Step2:
Configure the swagger plug-in.
Write a configuration class to implement the WebMvcConfigurer interface (it can not be implemented), which is used to configure Swagger related information.
@ EnableSwagger2 is used to turn on Swagger.

package com.lyh.test.test_mybatis_plus.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            // Plus ApiOperation Only annotated classes can generate interface documents
            .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
            // Specify the class under the package to generate the interface document
            .apis(RequestHandlerSelectors.basePackage("com.lyh.test.test_mybatis_plus.controller"))
            .paths(PathSelectors.any())
            .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("Swagger test")
            .description("Swagger Test documentation")
            .termsOfServiceUrl("https://www.cnblogs.com/l-y-h/")
            .version("1.0.0")
            .build();
    }
}

 

 

(3) Start the service and visit the swagger-ui.html page.
Visit http://localhost:8080/swagger-ui.html, as shown below. You can enter the online interface document page. Because there is no annotation on the method, the interface methods are not displayed.

 

 

(4) Add comments to interface methods.
Because the method with @ ApiOperation annotation annotation configured can be scanned, the annotation is added to the method.

@RestController
@RequestMapping("/test_mybatis_plus/user")
public class UserController {
    @Autowired
    private UserService userService;

    @ApiOperation("Get all users")
    @GetMapping("/test")
    public Result list() {
        return Result.ok().data("items", userService.list());
    }
}

 

 

(5) Restart the service and visit the swagger-ui.html page again.

 

 

 

 

 

 

 

 

2, Swagger annotation, configuration

1. Swagger common notes

(1) Common notes
swagger implements interface documents through annotations, which can mark interface names, request methods, parameters, return information, etc.

@Api is labeled on the controller class to decorate the controller
 @API operation is marked on the interface method to decorate the interface method
 @ApiParam is marked on the interface parameter to decorate the parameter
 @ApiImplicitParam is marked on the interface parameter to decorate a request parameter
 @ApiImplicitParams is marked on the interface parameters to decorate multiple request parameters (@ ApiImplicitParam)
@ApiIgnore is marked on the method and parameter, indicating that the method and parameter are ignored
 @ApiModel is marked on entity class to decorate entity class
 @ApiModelProperty is marked on the property of entity class to decorate the property of entity class.

 

(2) Example @ Api @ apioperation @ apiimplicitparam @ apiimplicitparam:

import com.lyh.test.test_mybatis_plus.entity.User;
import com.lyh.test.test_mybatis_plus.service.UserService;
import com.lyh.test.test_mybatis_plus.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  Front end controller
 * </p>
 *
 * @author lyh
 * @since 2020-05-08
 */
@RestController
@RequestMapping("/test_mybatis_plus/user")
@Api(value = "UserController", tags = "User interface documentation")
public class UserController {
    @Autowired
    private UserService userService;

    @ApiOperation("Get all users")
    @GetMapping("/list")
    public Result list() {
        return Result.ok().data("items", userService.list());
    }

    // paramType ="query" corresponding @RequestParam
    // paramType ="path" corresponding @PathVariable
    // paramType ="body" corresponding @RequestBody Not often used
    // paramType ="header" corresponding @RequestHeader
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", required = false, value = "user ID", paramType ="query", dataType = "Long"),
            @ApiImplicitParam(name = "user", required = false, value = "User information", paramType ="body", dataType = "User")
    })
    @ApiOperation("New users")
    @PutMapping("/update")
    public Result update(@RequestBody User user, @RequestParam(required = false) Long id) {
        System.out.println("==================");
        System.out.println(id);
        if (userService.save(user)) {
            return Result.ok().message("Data updated successfully");
        } else {
            return Result.error().message("Data update failed");
        }
    }
}

 

 

 

 

(3) Examples of @ ApiModel, @ ApiModelProperty

@Data
@ApiModel("Uniform result return class structure")
public class Result {
    /**
     * Whether the response is successful, true means success, false means failure
     */
    @ApiModelProperty("Whether the response is successful, true For success, false Failed for")
    private Boolean success;

    /**
     * Response status code, 200 successful, 500 system abnormal
     */
    @ApiModelProperty("Response status code, 200 successful, 500 system abnormal")
    private Integer code;

    /**
     * Response message
     */
    @ApiModelProperty("Response message")
    private String message;

    /**
     * Response data
     */
    @ApiModelProperty("Response data")
    private Map<String, Object> data = new HashMap<>();
}

 

 

 

 

2. Swagger configuration

(1) Introduction
The above is a brief introduction to the common annotations of swagger. Here is a brief introduction to the configuration class of swagger.

(2) Configuration class example
Modify apiInfo, apis, paths and other information according to the project situation.
Among them:
apiInfo is used to define the basic information of the interface document.
apis is used to define interface scanning rules.
paths is used to define path filtering rules.

@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            // Plus ApiOperation Only annotated classes can generate interface documents
            .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
            // Specify the class under the package to generate the interface document
            .apis(RequestHandlerSelectors.basePackage("com.lyh.test.test_mybatis_plus.controller"))
            .paths(PathSelectors.any())
            .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("Swagger test")
            .description("Swagger Test documentation")
            .termsOfServiceUrl("https://www.cnblogs.com/l-y-h/")
            .version("1.0.0")
            .build();
    }
}

 

(3) Analysis
Step 1: take a brief look at the annotations.
The @ EnableSwagger2 annotation is used to turn on swagger.
The @ Bean annotation indicates that the createRestApi method is used to instance the Docket object (document plug-in) and submit it to the Spring container for management.

Step 2: take a brief look at apiInfo.
This method is used to define the basic information of the API document.

[Brief introduction to properties:]
    title                  Title, default is Api Documentation
    version                Version, default is 1.0
    description            Description information, default is Api Documentation
    termsOfServiceUrl      Service address, default is urn:tos
    license                License, default is Apache 2.0
    licenseUrl             License address, default is http://www.apache.org/licenses/LICENSE-2.0
    contact                Define author information

[Example:]

private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
        .title("Background management system API file")
        .description("This document describes the definition of relevant interfaces of background management system")
        .termsOfServiceUrl("https://www.cnblogs.com/l-y-h/")
        .version("1.0.0")
        .contact(new Contact("lyh", "https://www.cnblogs.com/l-y-h/", "13865561381@163.com"))
        .build();
}

 

 

Step 3: take a brief look at the Docket
Docket implements the DocumentationPlugin interface, which is a document plug-in.
Introduction to common methods of Docket.

[common methods of Docket:]
    apiInfo() is used to define the basic information of the interface document.
    enabled() is used to define whether swagger is used.
    select() instantiates an ApiSelectorBuilder and calls its build method to return a dock object. 
    
[common methods of ApiSelectorBuilder:]
    apis() is used to define the interface scanning method (you can use RequestHandlerSelectors to specify the scanning rules)
    paths() is used to filter paths (you can use PathSelectors to specify filter rules).
    build() returns a dock object
 Note:
    RequestHandlerSelectors common methods:
       any() scan all
       none() do not scan all
       withMethodAnnotation() scans based on the annotation on the method
       withClassAnnotation() scans based on the annotation on the class
       basePackage() specifies the package to scan
  
   Common methods of PathSelectors:
       any() all passed
       none() all failed
       Whether regex() passes according to regular expression matching
       
[example]

@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {
    @Value("${spring.profiles.active:#{null}}")
    private String env;

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            //Specifies whether to turn on swagger (as follows, no swagger is executed in the production environment)
            .enable("prod".equals(env) ? false : true)
            //Specify group name
            .groupName("user")
            .select()
            //Only classes annotated with ApiOperation can generate interface documents
            .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
            //Specify the class under the package to generate the interface document
            .apis(RequestHandlerSelectors.basePackage("com.lyh.test.test_mybatis_plus.controller"))
            //Unfiltered interface
            .paths(PathSelectors.any())
            .build();
    }
}

Topics: Java Spring Apache REST