Swagger study notes

Swagger

Learning objectives

  • Understand the role and concept of Swagger
  • Understand front and rear end separation
  • Integrating Swagger in SpringBoot

About Swagger

Front and rear end separation
Vue + SpringBoot
Post era: the front end only manages static pages; html – > last paragraph. The latter part of the template engine JSP - > is the main force

Era of front and rear end separation:

  • Back section: the back section is controlled into service layer and data access layer [back section team]
  • Front end, front end control layer, view layer [ front end team ]
    • Forge the data of the later segment, json. Data forgery does not need the back stage, and front-end engineering can still run
  • Front and back end data interaction - > API
  • The front and rear ends are relatively independent and loosely coupled
  • The front and back end can even be deployed on different servers

A problem arises:

  • The front and rear end integration and joint commissioning failed to negotiate new requirements in time and solve them as soon as possible, resulting in centralized outbreak of problems

Solution:

  • Develop a schema [outline of the plan] to update the latest API in real time to reduce the risk of integration
  • Early years: develop Word plan documents
  • Front and rear end separation:
    • Front end test rear section interface: postman
    • The latter section 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 generation tool = > Api document and Api definition are updated synchronously
  • Run directly, and you can test the Api interface online
  • Support multiple languages (Java, Php...)

Official website: Official website link

Using Swagger in a project requires a springbox;

  • swagger2
  • ui

SpringBoot integration Swagger

1. Create a new springboot web project
2. Import related dependencies

<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 HelloWord project
4. Configure Swagger – > config

@Configuration//Configure into configuration
@EnableSwagger2//Turn on Swagger2
public class SwaggerConfig {
}

5.http://localhost:8080/swagger-ui.htmltest run

Configure Swagger

Swagger's bean instance Docket

@Configuration//Configure into configuration
@EnableSwagger2//Turn on Swagger2
public class SwaggerConfig {

    //Configured the Bean instance of Swagger
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo());
    }

    //Configure swagger information = apiInfo
    private ApiInfo apiInfo(){

        //Author information
        Contact contact = new Contact("zdq", "https://blog.csdn.net/perfect_zdq", "15111830814@163.com");
            return new ApiInfo(
                    "In self-study SwaggerAPI file"
                    , "The harder you work, the luckier you are!"
                    , "1.0"
                    , "https://blog.csdn.net/perfect_zdq"
                    , contact
                    , "Apache 2.0"
                    , "http://www.apache.org/licenses/LICENSE-2.0"
                    , new ArrayList());
    }
}

Swagger configuration scan interface

Docket.select()

//Configured the Bean instance of Swagger
@Bean
public Docket docket(){
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            //RequestHandlerSelectors: configure how to scan interfaces
            //basePackage: Specifies the package to scan
            //any(): scan all
            //none(): do not scan
            //withClassAnnotation(): scan the annotation on the class. The parameter is a reflection object of the annotation
            //withMethodAnnotation(): scan annotations on Methods
            .apis(RequestHandlerSelectors.basePackage("com.zdq.swagger.controller"))
            //paths(): what paths are filtered
            .paths(PathSelectors.ant("/zdq/**"))
            .build();
}

Configure whether to start Swagger

//Configured the Bean instance of Swagger
@Bean
public Docket docket(){
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            //enable(false): whether to enable Swagger. If false, Swagger cannot be accessed in the browser
            .enable(false)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.zdq.swagger.controller"))
            //.paths(PathSelectors.ant("/zdq/**"))
            .build();
}

Swagger is used in the development environment and will not be used after the official release

  • Judge whether it is a production (Development) environment flag = false
  • Injection enable (true)
@Bean
public Docket docket(Environment environment){
//Set up a realistic Swagger environment
Profiles profiles = Profiles.of("dev","test");
//Get the environment of the project
boolean flag = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        //enable(false): whether to enable Swagger. If false, Swagger cannot be accessed in the browser
        .enable(flag)
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.zdq.swagger.controller"))
        //.paths(PathSelectors.ant("/zdq/**"))
        .build();
}

Configure grouping of API documents

.groupName("My group")

Configure multiple groups and multiple Docket instances

@Bean
public Docket docket1(){
    return new Docket(DocumentationType.SWAGGER_2).groupName("A");
}

@Bean
public Docket docket2(){
    return new Docket(DocumentationType.SWAGGER_2).groupName("B");
}

@Bean
public Docket docket3(){
    return new Docket(DocumentationType.SWAGGER_2).groupName("C");
}

Entity class configuration

@ApiModel("User class entity")
public class User {

    @ApiModelProperty("user name")
    public String userName;
    @ApiModelProperty("User password")
    public String passWord;
}

Controller configuration

@Api(tags = "Interface notes")
@RestController
public class HelloController {

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String hello(){
        return "hello";
    }

    @GetMapping(value = "/user")
    public User user(){
        return new User();
    }

    @ApiOperation("Method Chinese Notes")
    @GetMapping("/hello2")
    public String hello2(@ApiParam("user name") String name){
        return "hello" + name;
    }

    @ApiOperation("Post Test class")
    @PostMapping("/postt")
    public User postt(@ApiParam("user name") User user){
        int i = 5/0;
        return user;
    }
}

Summary:
1. Add annotation information to some properties or interfaces that are difficult to understand through Swagger
2. Real time update of interface documents
3. It can be tested online

Attention
Close Swagger at the official launch! For security reasons and can save memory

Tags: Java api API testing swagger2

Posted on Tue, 05 Oct 2021 19:41:30 -0400 by michaelh613