Introduction of Swagger

Learning Objectives:

  • Understand the concept and function of Swagger
  • Master the integration of Swagger into projects to automatically generate API documentation

Swagger coordinates front and rear end separation

Front end separation

  • Front -> Front control layer, view layer
  • Back-end -> back-end control layer, service layer, data access layer
  • The front and back ends interact through apis
  • The front and back ends are relatively independent and loosely coupled

Problems arising

  • The front and back ends are integrated. The front and back ends cannot negotiate timely and resolve problems as soon as possible

The solution

  • First define the schema and keep track of the latest apis in real time to reduce integration risks

Swagger

  • The most popular API framework in the world
  • Api documents are automatically generated online => Api documents are updated with Api definitions
  • Run directly, test the API online
  • Support for multiple languages (e.g. Java, PHP, etc.)
  • Liverpoolfc.tv: swagger. IO /

SpringBoot integration Swagger

SpringBoot with Swagger => SpringFox, two JAR packages

  • Springfox-swagger2
  • swagger-springmvc

Use the Swagger

Required: JDK 1.8 + otherwise Swagger2 will not run

Steps:

1. Create a SpringBoot-Web project

2. Add Maven dependencies

<! -- 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>
Copy the code

3, write HelloController, test to ensure success!

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

@Configuration / / configuration class
@EnableSwagger2// Enable automatic configuration of Swagger2
public class SwaggerConfig {}Copy the code

5, start springboot access test: http://localhost:8080/swagger-ui.html, you can see the swagger interface:

Configuration Swagger

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

@Bean // Configure docket to configure Swagger
public Docket docket(a) {
   return new Docket(DocumentationType.SWAGGER_2);
}
Copy the code

2. Document information can be configured using the apiInfo() property

// Configure the document information
private ApiInfo apiInfo(a) {
   Contact contact = new Contact("Contact name"."http://xxx.xxx.com/ Contact access link"."Contact Email");
   return new ApiInfo(
           "Swagger learning"./ / title
           "Learn how to configure Swagger"./ / description
           "v1.0"./ / version
           "Http://terms.service.url/ organization links".// Organize links
           contact, // Contact information
           "Apach 2.0 License"./ / permission
           "Permission link".// Permit connection
           new ArrayList<>()/ / extension
  );
}
Copy the code

Docket instance apiInfo()

@Bean
public Docket docket(a) {
   return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
}
Copy the code

4, restart the project, access to test under http://localhost:8080/swagger-ui.html effect;

Configuring scan Interfaces

Swagger documents access this page by default:

Select () when building a Docket to configure how to scan interfaces.

@Bean
public Docket docket(a) {
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .select()Select (). RequestHandlerSelectors configure how to scan interfaces
      .apis(RequestHandlerSelectors.basePackage(
          "com.kuang.swagger.controller"))
      .build();
}
Copy the code

2, restart the project test, because we configured the scan interface by package path, we can only see one class

3. In addition to configuring the scanning interface through the packet path, you can also configure other scanning interfaces. Here are some comments on all configuration modes:

any() // Scan all. All interfaces in the project will be scanned
none() // Do not scan interfaces
// Scan with annotations on methods, such as withMethodAnnotation(getMapping.class) only scan get requests
withMethodAnnotation(final Class<? extends Annotation> annotation)
WithClassAnnotation (Controller.class) scans only interfaces in classes that have Controller annotations
withClassAnnotation(final Class<? extends Annotation> annotation)
basePackage(final String basePackage) // Scan interfaces based on packet paths
Copy the code

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

@Bean
public Docket docket(a) {
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .select()Select (). RequestHandlerSelectors configure how to scan interfaces
      .apis(RequestHandlerSelectors.basePackage(
          "com.kuang.swagger.controller"))
       // How to configure filtering through PATH, that is, only scan interfaces whose requests start with /kuang
      .paths(PathSelectors.ant("/kuang/**"))
      .build();
}
Copy the code

5. There are also optional values

any() // Any request is scanned
none() // No requests are scanned
regex(final String pathRegex) // Control with regular expressions
ant(final String antPattern) // Control by ant()
Copy the code



Configure Swagger switch

1. Use the enable() method to enable swagger. If swagger is false, swagger is not accessible in the browser

@Bean
public Docket docket(a) {
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .enable(false) // Configures whether Swagger is enabled. If false, it will not be accessible in the browser
      .select()Select (). RequestHandlerSelectors configure how to scan interfaces
      .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
       // How to configure filtering through PATH, that is, only scan interfaces whose requests start with /kuang
      .paths(PathSelectors.ant("/kuang/**"))
      .build();
}
Copy the code

2. How to dynamically configure swagger to be displayed when the project is in test or dev environment, but not when the project is in PROD?

@Bean
public Docket docket(Environment environment) {
   // Set the environment to display Swagger
   Profiles of = Profiles.of("dev"."test");
   // Determine whether the current environment
   // Accept this parameter with enable() to determine whether to display
   boolean b = environment.acceptsProfiles(of);
   
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .enable(b) // Configures whether Swagger is enabled. If false, it will not be accessible in the browser
      .select()Select (). RequestHandlerSelectors configure how to scan interfaces
      .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
       // How to configure filtering through PATH, that is, only scan interfaces whose requests start with /kuang
      .paths(PathSelectors.ant("/kuang/**"))
      .build();
}
Copy the code

3, you can add a dev configuration file to the project to see the effect!

[Img-wV2RqD54-1600066716545] (D:\Note\ Note\ Middleware \ Swagger \ Swagger. Assets \640)

Configuring API Grouping

[Img-xFQelryh-1600066716547] (D:\Note\ Note\ Middleware \ Swagger \ Swagger. Assets \640) The default value is default. GroupName () can be used to configure groups:

@Bean
public Docket docket(Environment environment) {
   return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
      .groupName(One Piece) // Set the group name
       // Omit the configuration....
}
Copy the code

2. Restart the project to view groups

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

 @Bean
 public Docket docket1(a){
     return new Docket(DocumentationType.SWAGGER_2).groupName("The road");
 }
 @Bean
 public Docket docket2(a){
     return new Docket(DocumentationType.SWAGGER_2).groupName("Sanji");
 }
 @Bean
 public Docket docket3(a){
     return new Docket(DocumentationType.SWAGGER_2).groupName("Sauron");
 }
Copy the code

4. Restart the project and view it, as shown in the picture:

Insert a picture description here

Physical configuration

Create a new entity class

@apiModel (" user entity ")
public class User {
   @apiModelProperty (" username ")
   public String username;
   @ ApiModelProperty (" password ")
   public String password;
}
Copy the code

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

// As long as this entity is on the return value of the request interface (even if it is generic), it can be mapped to the entity item
@PostMapping("/user")
public User user(a){
    return new User();
}
Copy the code

3. Restart the test

[Img-drrkitto-1600066716549] (D:\Note\ Note\ Middleware \ Swagger \swagger. Assets \640)

Note: This is not because the @APIModel annotation makes the entity appear here, but because any entity that appears on the return value of the interface method will appear here. The @APIModel and @APIModelProperty annotations only comment the entity.

@apiModel adds comments to the class

@apiModelProperty adds comments to class attributes

Commonly used annotations

Annotations all annotations of Swagger are defined under the IO. Swagger. Annotations package

The following list of some frequently used, not listed can be consulted separately:

Swagger annotations Simple instructions
@API (tags = “XXX module description”) Applies to module classes
@apiOperation (” XXX interface description “) Applies to interface methods
@ ApiModel (” xxxPOJO instructions “) Works on model classes: VO, POJO, Entity
@APIModelProperty (value = “XXX attribute description”,hidden = true) Applied to class methods and properties, hidden is set to true to hide the property
@apiParam (” XXX Parameter Description “) Applies to parameters, methods, and fields, similar to @apiModelProperty

We can also configure some annotations for the requested interface

/ * * *@Auther: csp1999
 * @Date: 2020/09/06/11:11
 * @Description: * /
@api (tags = "Hello control class ")
@RestController
public class HelloController {

    @GetMapping("/hello")
    public String helloController(a){

        return "hello";
    }

    // As long as this entity is on the return value of the request interface (even if it is generic), it can be mapped to the entity item
    @apiOperation (" Hello control class user method ")
    @PostMapping("/user")
    public User user(@apiparam (" username ") String username){

        return newUser(); }}Copy the code

In this way, you can add some configuration information to some properties or interfaces that are difficult to understand, making them easier to read!

As shown in figure:

Compared to the traditional Postman or Curl test interface, using Swagger is a foolproof operation. It does not require additional documentation (well written is documentation itself) and is less prone to errors. You just need to input data and click Execute.

Swagger is an excellent tool, and now many small and medium-sized Internet companies in China are using it. Compared with the traditional way of first producing Word interface documents and then testing, it is obviously more in line with the current rapid iterative development market. Of course, remember to turn Off Swagger in the formal environment, both for security reasons and to save runtime memory.

Test data acquisition

To send the request data, click execute:

The result of the response back:

Expansion: Other skins

We can import different packages to implement different skin definitions:

1, the default of http://localhost:8080/swagger-ui.html

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

[img-oyveU8LD-1600066716554] (D: Note Note Middleware swagger swagger. Assets 640) [IMg-oyveU8LD-1600066716554]

2, the bootstrap – UI to http://localhost:8080/doc.html

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

[ImG-rCFhXKFA-1600066716555] (D: Note Note Middleware swagger swagger.assets 640) [IMG-rCFhXKFA-1600066716555]

3, Layui – UI to http://localhost:8080/docs.html

<! -- Introducing swagger-uI-Layer package /docs.html-->
<dependency>
   <groupId>com.github.caspar-chen</groupId>
   <artifactId>swagger-ui-layer</artifactId>
   <version>1.1.3</version>
</dependency>
Copy the code

[Img-ydlgXhxZ-1600066716556] [IMg-ydLGXhxz-1600066716556] (D: Note Note Middleware swagger swagger.assets 640)

4, mg – UI to http://localhost:8080/document.html

<! Swagger uI-Layer package /document.html-->
<dependency>
   <groupId>com.zyplayer</groupId>
   <artifactId>swagger-mg-ui</artifactId>
   <version>1.0.6</version>
</dependency>
Copy the code

[ImG-bjtForbF-1600066716557] (D:\Note\ Note\ Middleware \ Swagger \swagger. Assets \640)