Swagger notes (MAD God)

Swagger

The video tutorial comes from madness and says: https://space.bilibili.com/95256449

Notes from: https://blog.csdn.net/weixin_44635198/article/details/107721418

  • Understand the concept and function of Swagger
  • Understand front and rear end separation
  • Integrating swagger in spring boot

1. About Swagger

Front and rear end separation

Vue+SpringBoot

Back end era: the front end only manages static pages; HTML = = > back end. Template engine JSP = > the back end is the main force

Era of front and rear end separation

Vue+SpringBoot

Back end era: the front end only manages static pages; HTML = = > back end. Template engine JSP = > the back end is the main force

Era of front and rear end separation

  • Front end - > front end control layer, view layer

  • Forge back-end data, json. It already exists. The front-end engineering team can still run without a back-end

  • Backend - > backend control layer, service layer and data access layer

  • The front and back end interact through API

  • The front and rear ends are relatively independent and loosely coupled

Problems arising

  • The front-end and back-end integration and joint commissioning, the front-end or back-end can not achieve "timely negotiation and early solution", which eventually leads to the centralized outbreak of problems

Solution

  • First, define the schema [outline of the plan] and track the latest API in real time to reduce the integration risk;
  • Previous years: specify the word plan document;
  • Front and rear end separation:
    • Front end test back end interface: postman
    • The back-end provides an interface, which needs to update the latest messages and changes in real time

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/

2. SpringBoot integration Swagger

SpringBoot integrates swagger = > springfox, two jar packages

Using Swagger

Requirement: jdk 1.8 + otherwise swagger2 cannot run

Steps:

  1. Create a new springboot web project

  2. Add Maven dependency (Note: before version 2.9.2, not after version 2.9.2)

<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>
  1. Write HelloController and test to ensure successful operation!

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

@Configuration //Configuration class
@EnableSwagger2// Turn on automatic configuration of Swagger2
public class SwaggerConfig {  
}
  1. Access test: http://localhost:8080/swagger-ui.html, you can see the interface of swagger;

3. Configure Swagger

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

    A bean is actually an instance object
    However, bean is an exclusive concept in spring (or similar framework or container)

    Ordinary new objects are called objects.
    But you leave this object to spring for management (through component s and so on), so that every time you don't need new in the code, it becomes a bean

@Bean //Configure the docket to configure Swagger specific parameters
public Docket docket() {
   return new Docket(DocumentationType.SWAGGER_2);
}
  1. You can configure the document information through the apiInfo() property
//Configure document information
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
  );
}
  1. apiInfo() on Docket instance Association
@Bean
public Docket docket() {
   return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
}
  1. Restart the project and access the test http://localhost:8080/swagger-ui.html to see the effect;

4. 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("nuc.ss.swagger.controller"))
      .build();
}
  1. Restart the project test. Since we configured to scan the interface according to the path of the package, we can only see one class

  1. 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:
basePackage(final String basePackage) // Scan interface according to packet path
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)
  1. In addition, we can also configure interface scanning filtering:
@Bean
public Docket docket() {
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .select()
      .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
       // Configure how to filter through path, that is, only the interfaces whose requests start with / ss are scanned here
      .paths(PathSelectors.ant("/ss/**"))
      .build();
}
  1. 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()

5. 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) //Configure whether Swagger is enabled. If false, it will not be accessible in the browser
      .select()
      .apis(RequestHandlerSelectors.basePackage("nuc.ss.swagger.controller"))
      .paths(PathSelectors.ant("/ss/**"))
      .build();
}

  1. 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 of = Profiles.of("dev", "test");
   // Judge whether you are currently in this environment
   // Receive this parameter through enable() to determine whether to display
   boolean b = environment.acceptsProfiles(of);
   
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .enable(b)
      .select()
      .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
      .paths(PathSelectors.ant("/ss/**"))
      .build();
}
  1. You can add a profile to the project
  • dev test environment

    server.port=8081
    

Project operation results

  1. pro test environment
server.port=8082

Project operation results

6. Configure API grouping

  1. If grouping is not configured, the default is default. Grouping can be configured through the groupName() method:
@Bean
public Docket docket(Environment environment) {
   return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
      .groupName("Mad God") // Configure grouping
       // Omit configuration
}
  1. Restart item view group

  1. 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");
}

  1. Restart the project to view it

7. Entity configuration

  1. Create a new entity class
//@Api("notes")
@ApiModel("User entity")
public class User {
    @ApiModelProperty("user name")
    private String username;
    @ApiModelProperty("password")
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
  1. As long as the entity is on the return value of the request interface (even generic), it can be mapped to the entity item:
@RestController
public class HelloController {

    //   /Error default error request
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    //As long as there is an entity class in the return value in our interface, it will be scanned into Swagger
    @PostMapping("/user")
    public User user() {
        return new User();
    }
}

  1. Restart view test

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

  • @ApiModel adds comments to the class

  • @ApiModelProperty adds comments for class properties

Summary:

  • We can add annotation information to some difficult interfaces or attributes through Swagger
  • Real time update of interface documents
  • It can be tested online

Swagger is an excellent tool, which is used by almost all large companies

[note]: close Swagger during official release!!!

  • For safety reasons
  • And save memory

8. Common notes

All annotations of Swagger are defined under the io.swagger.annotations package

Some frequently used are listed below, and those not listed can be consulted separately:

We can also configure some comments for the requested interface

  1. Add an api interface annotation to the interface in the HelloController control class
@RestController
public class HelloController {
    ......
    @ApiOperation("Hello control interface ")
    @GetMapping("/hello")
    public String hello2(@ApiParam("user name") String username) {
        return "hello" + username;
    }
    
    @ApiOperation("get test")
    @GetMapping("/get")
    public User hello2(@ApiParam("user") User user) {
        return user;
    }
}

  1. try it out

test result

Summary:

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

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

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

9. Expansion: other skin

We can import different packages to implement different skin definitions:

1. Default access http://localhost:8080/swagger-ui.html

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

2. Bootstrap UI access http://localhost:8080/doc.html

<!-- introduce swagger-bootstrap-ui package /doc.html-->
<dependency>
   <groupId>com.github.xiaoymin</groupId>
   <artifactId>swagger-bootstrap-ui</artifactId>
   <version>1.9.1</version>
</dependency>

3. Layui UI access http://localhost:8080/docs.html

<!-- introduce swagger-ui-layer package /docs.html-->
<dependency>
   <groupId>com.github.caspar-chen</groupId>
   <artifactId>swagger-ui-layer</artifactId>
   <version>1.1.3</version>
</dependency>
  • My test failed (layui UI)

4. Mg UI access http://localhost:8080/document.html

<!-- introduce swagger-ui-layer package /document.html-->
<dependency>
   <groupId>com.zyplayer</groupId>
   <artifactId>swagger-mg-ui</artifactId>
   <version>1.0.6</version>
</dependency>

  • My test failed (layui UI)

4. Mg UI access http://localhost:8080/document.html

<!-- introduce swagger-ui-layer package /document.html-->
<dependency>
   <groupId>com.zyplayer</groupId>
   <artifactId>swagger-mg-ui</artifactId>
   <version>1.0.6</version>
</dependency>

Tags: Java Spring Boot Interview swagger2

Posted on Tue, 28 Sep 2021 23:06:44 -0400 by platnium