Swagger study notes

Keywords: Java Spring Boot RESTful swagger

About Swagger

Front and rear end separation

  • Front end: front end control layer, view layer
  • Back end: back end control layer, service layer and data access layer
  • The front and back ends interact through Api
  • The front and rear ends are relatively independent and loosely coupled

Problems arising

  • During front-end and back-end integration, the front-end or back-end cannot "negotiate in time and solve it as soon as possible", and finally the problems erupt.

Solution

  • First, define the schema [outline of the plan] and track the latest API in real time to reduce the integration risk

Swagger

  • It is known as the most popular API framework in the world
  • Restful Api document online automatic generator = > API document and API definition are updated synchronously
  • Direct run, online test API
  • Support multiple languages (such as Java, PHP, etc.)
  • Official website: https://swagger.io/

SpringBoot integration Swagger

1. Create a new springboot web project

2. Add Maven dependency

 <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>

3. Write HelloController and test to ensure successful operation!

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }
}

4. To use Swagger, we need to write a configuration class SwaggerConfig to configure Swagger

@Configuration
@EnableSwagger2
public class SwaggerConfig {
}

5. Access test: http://localhost:8080/swagger-ui.html, you can see the interface of swagger:

Configure Swagger

1. Swagger instance Bean is a Docket, so configure swagger by configuring the Docket instance.

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2);
    }
}

2. You can configure the document information through the apiInfo() property

@Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
    }
    private ApiInfo apiInfo(){
        Contact contact = new Contact("Contact name", 
                                       "http://xxx.xxx.com/ contact access link ", 
                                      "Contact email");
        return new ApiInfo(
                "Swagger study", // title
                "Learn to demonstrate how to configure Swagger", // describe
                "v1.0", // edition
                "http://terms.service.url/ organization link ", / / organization link
                contact, // contact information 
                "Apach 2.0 permit", // permit
                "License link", // License connection
                new ArrayList<>()// extend
                 );
    }

4. Restart the project and access the test http://localhost:8080/swagger-ui.html see the following effect:

Configure scan interface

1. When building a Docket, configure how to scan the interface through the select() method.

 @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()// Configure the scanning interface through the. select() method, and RequestHandlerSelectors configure how to scan the interface
                .apis(RequestHandlerSelectors.basePackage("com.orange.swagger.controller"))
                .build();
    }

2. Restart the project test. Since we configured to scan the interface according to the path of the package, we can only see one class

You can see that there is no Error, only HelloController

3. In addition to configuring the scanning interface through the package path, you can also configure other methods to scan the interface. Here are all the configuration methods:

    any() // All interfaces in the project will be scanned
    none() // Do not scan interfaces
    // Scan the annotation on the method, such as withMethodAnnotation(GetMapping.class), and only scan the get request
    withMethodAnnotation(final Class<? extends Annotation> annotation)
    // Scan the annotation on the class, such as. withClassAnnotation(Controller.class). Only scan the interface in the class with controller annotation
    withClassAnnotation(final Class<? extends Annotation> annotation)
    basePackage(final String basePackage) // Scan interface according to packet path

4. In addition, we can also configure interface scanning filtering:

@Bean
public Docket docket() {
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .select()// Configure the scanning interface through the. select() method, and RequestHandlerSelectors configure how to scan the interface
      .apis(RequestHandlerSelectors.basePackage("com.orange.swagger.controller"))
       // Configure how to filter through path, that is, only the interfaces whose requests start with / kuang are scanned here
      .paths(PathSelectors.ant("/orange/**"))
      .build();
}

5. The optional values here are

any() // Scan any request
none() // No requests are scanned
regex(final String pathRegex) // Regular expression control
ant(final String antPattern) // Controlled by ant()

Configure Swagger switch

1. Configure whether to enable swagger through the enable() method. If false, swagger will not be accessible in the browser

    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(false)
                .select()// Configure the scanning interface through the. select() method, and RequestHandlerSelectors configure how to scan the interface
                .apis(RequestHandlerSelectors.basePackage("com.orange.swagger.controller"))
                .build();
    }

Run test:

2. How to dynamically configure the display of swagger when the project is in the test and dev environment and not when it is in prod?

    @Bean
    public Docket docket(Environment environment){
        // Set the environment in which you want to display swagger
        Profiles profiles = Profiles.of("test", "dev");
        // Judge whether you are currently in this environment
        // Receive this parameter through enable() to determine whether to display
        boolean flag = environment.acceptsProfiles(profiles);
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(flag)
                .select()// Configure the scanning interface through the. select() method, and RequestHandlerSelectors configure how to scan the interface
                .apis(RequestHandlerSelectors.basePackage("com.orange.swagger.controller"))
                .build();
    }

3. You can add a dev configuration file to the project to see the effect!

Configure API grouping

1. If grouping is not configured, the default is default. Grouping can be configured through the groupName() method:

  return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("hello")

2. Restart item view group

3. How to configure multiple groups? To configure multiple groups, you only need to configure multiple docks:

@Bean
public Docket docket1(){
   return new Docket(DocumentationType.SWAGGER_2).groupName("group1");
}
@Bean
public Docket docket2(){
   return new Docket(DocumentationType.SWAGGER_2).groupName("group2");
}
@Bean
public Docket docket3(){
   return new Docket(DocumentationType.SWAGGER_2).groupName("group3");
}

4. Restart the project to view it

Entity configuration

1. Create a new entity class

@ApiModel("User entity class")
public class User {
    @ApiModelProperty("user name")
    public String userName;
    @ApiModelProperty("password")
    public String Password;
}

2. As long as the entity is on the return value of the request interface (even generic), it can be mapped to the entity item:

 @PostMapping("/user")
    public User getUser(){
        return new User();
    }
}

3. Restart view test

Note: it is not because the @ ApiModel annotation makes the entity displayed here, but as long as the entity that appears on the return value of the interface method will be displayed here, and the @ ApiModel and @ ApiModelProperty annotations only add annotations to the entity.

  • @ApiModel adds comments to the class
  • @ApiModelProperty adds comments for class properties

Common notes

All annotations of Swagger are defined in the io.swagger.annotations package. The following are some frequently used annotations. For those not listed, please refer to the instructions separately:

Swagger annotationBrief description
@Api(tags = "xxx module description")@Api(tags = "xxx module description")
@ApiOperation("xxx interface description")Act on interface methods
@ApiModel("xxxPOJO description")Act on model classes: such as VO and BO
@ApiModelProperty(value = "xxx property description", hidden = true)It acts on class methods and attributes. Setting hidden to true can hide the attribute
@ApiParam("xxx parameter description")It acts on parameters, methods and fields, similar to @ ApiModelProperty

We can also configure some comments for the requested interface

@ApiOperation("Interface of madness")
@PostMapping("/kuang")
@ResponseBody
public String kuang(@ApiParam("This name will be returned")String username){
   return username;
}

In this way, you can add some configuration information to some difficult attributes or interfaces to make it easier for people to read!

Compared with the traditional Postman or Curl test interface, using swagger is a fool's operation. It does not need additional description documents (well written documents are themselves documents) and is less prone to errors. It only needs to enter data and click Execute. If it is combined with the automation frame, it can be said that there is basically no need for human operation.

Swagger is an excellent tool. At present, many small and medium-sized Internet companies in China are using it. Compared with the traditional way of first outputting Word interface documents and then testing, it is obviously more in line with the current rapid iterative development market. Of course, I would like to remind you to turn off swagger in the formal environment. First, for security reasons, and second, you can save runtime memory.

Posted by chetanrakesh on Mon, 04 Oct 2021 14:39:25 -0700