SpringBoot integrated interface management tool Swagger

Swagger

Introduction to Swagger

Springboot integrates swagger

Swagger Common Annotations

1. Introduction to Swagger

​ Swagger is a series of RESTful API tools. Through Swagger, you can get an interactive document of the project, automatic generation of client SDK and other functions.

​ The goal of Swagger is to define a standard, language-independent interface for REST APIs, so that people and computers can discover and understand various function of the service. When services are defined through Swagger, consumers can interact with remote services with a small amount of implementation logic. Swagger (stocking brother) is the most popular API expression tool in the world.

2. Springboot integrates swagger

​ The idea of ​​using Spring Boot to integrate Swagger is to use annotations to mark the information that needs to be displayed in the API documentation, and Swagger will generate the corresponding API documentation according to the annotations marked in the project. Swagger is known as the most popular API tool in the world. It provides a complete set of API management solutions. The factors that need to be considered in API document management are basically included. The most commonly used customized content will be explained here.

1. Add swagger coordinates

It is very simple to integrate Swagger 3 with Spring Boot, just need to introduce dependencies and do basic configuration.

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

2. Implementation of Swagger Helloword

2.1. Create a springboot project

Add the @EnableOpenApi annotation to the startup class to enable the swagger api document function

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.oas.annotations.EnableOpenApi;

@SpringBootApplication
@EnableOpenApi  //启动swagger api文档注解
public class SpringBootWithSwaggerApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(SpringBootWithSwaggerApplication.class, args);
    }

}

2.2, write an interface

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 阿水
 * @create 2023-04-11 9:54
 */
@RestController()
public class SwaggerController {
    
    
    @GetMapping ("hello")
    public String hello(String params) {
    
    
        return "hello swagger"+" param为:"+params;
    }
}

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-YhlXa2TH-1681180965655) (C:\Users\lps\AppData\Roaming\Typora\typora-user-images\ image-20230411100816692.png)]

2.3. Access address

http://localhost:8080/swagger-ui/index.html

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-ERv4KUyj-1681180965656) (C:\Users\lps\AppData\Roaming\Typora\typora-user-images\ image-20230411101334968.png)]

3. Commonly used configuration annotations

Swagger indicates through annotations that the interface will generate documents, including interface name, request method, parameters, return information, etc.

1. Api annotation and ApiOperation annotation

  • @Api

    When used on a class, it indicates that it is a swagger resource. @API has two attributes: value and tags.

    The generated api documents will be classified according to tags. To put it bluntly, the interface documents generated by all interfaces in this controller will be under the tags list; if tags have multiple values, multiple lists will be generated, and each list will display all interface

    value acts like tags, but cannot have multiple values

    语法:
      @Api(tags = "用户操作")
      或
      @Api(tags = {"用户操作","用户操作2"})
    
  • @ApiOperation

    Used in methods to represent the operation of an http request

    语法:
        @ApiOperation(value = "", 
                      notes = "", 
                      response = )
    属性说明:
      value:方法说明标题
      notes:方法详细描述
      response:方法返回值类型
    

    Case: Generate api documentation using @Api and @ApiOperation

    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * @author 阿水
     * @create 2023-04-11 9:54
     */
    @RestController()
    @Api(tags = {
          
          "操作用户"})
    public class SwaggerController {
          
          
        @GetMapping ("hello")
        @ApiOperation(value = "swagger请求",notes = "阿水的第一个swagger请求",response = String.class)
        public String hello(String params) {
          
          
            return "hello swagger"+" param为:"+params;
        }
    }
    

2. ApiImplicitParams annotation and ApiImplicitParam

The @ApiImplicitParams annotation and @ApiImplicitParam are used to describe non-object parameters in methods (used when parameters are bound to simple types.)

语法:
@ApiImplicitParams(value = {
     @ApiImplicitParam(name="", value = "", type = "", required = true, paramType = "", defaultValue  = "")
})

属性说明:
    name:形参名称
    value:形参的说明文字
    type:形参类型
    required:该参数是否必须  true|false
    paramType: 用于描述参数是以何种方式传递到 Controller 的,它的值常见有: path, query, body 和 header 
        path 表示参数是『嵌在』路径中的,它和 @PathVariable 参数注解遥相呼应;
    	query 表示参数是以 query string 的形式传递到后台的(无论是 get 请求携带在 url 中,还是 post 请求携带在请求体中),它和 @RequestParam 参数注解遥相呼应;
    	header 表示参数是『藏在』请求头中传递到后台的,它和 @RequestHeader 参数注解遥相呼应的。
    	form 不常用.
    defaultValue :参数默认值

Note: The name attribute of @ApiImplicitParam should echo the value of @RequestParam or @PathVariable.

Case: Use @ApiImplicitParams annotation and @ApiImplicitParam to describe method parameters

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 阿水
 * @create 2023-04-11 9:54
 */
@RestController()
@Api(tags = {
    
    "操作用户"})
public class SwaggerController {
    
    
    @GetMapping ("hello")
    @ApiOperation(value = "swagger请求",notes = "阿水的第一个swagger请求",response = String.class)
    @ApiImplicitParams(value ={
    
    
            @ApiImplicitParam(name="param1",
                    value = "参数名1",
                    type = "String",
                    required = true,
                    paramType = "query",
                    defaultValue  = "阿水所想的默认值1" ),
            @ApiImplicitParam(name="param2",
                    value = "参数名2",
                    type = "String",
                    required = true,
                    paramType = "query",
                    defaultValue  = "阿水所想的默认值2" )
    })
    public String hello(String param1,String param2) {
    
    
        return "hello swagger"+" param1为:"+param1+"param2为"+param2;
    }
}

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-fBArcPkc-1681180965656) (C:\Users\lps\AppData\Roaming\Typora\typora-user-images\ image-20230411102447841.png)]

3. ApiModel annotations and ApiModelProperty

  • @ApiModel

    It is used on the entity class to indicate the description of the class, and is used for the parameter receiving description in the entity class.

    语法:
        @ApiModel("用户类")
        public class Users {
          
          
        }
    
  • @ApiModelProperty

    Used to describe the attributes in the entity class

    @ApiModel("用户类")
    @Data
    public class Users {
          
          
    
        @ApiModelProperty(value = "编码:主键")
        private Integer id;
    
        @ApiModelProperty(value = "用户名")
        private String username;
    
        @ApiModelProperty(value = "密码")
        private String password;
    
    }
    

4、ApiResponse 和 ApiResponses

The @ApiResponses annotation and @ApiResponse are marked on the method of the Controller to describe the response of the HTTP request

/**
     * 添加用户
     *
     * @param user
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "添加用户",notes = "添加用户信息",response = ResponseResult.class)
    @ApiResponses({
    
     @ApiResponse(code = 200, message = "添加成功", response = ResponseResult.class),
            	    @ApiResponse(code = 500, message = "添加失败", response = ResponseResult.class) })
    public ResponseResult<Void> addUser(@RequestBody User user) {
    
    
        //获得生成的加密盐
        user.setSalt(SaltUtils.getSalt());
        int n = userService.addUser(user);
        if (n > 0) {
    
    
            return new ResponseResult<Void>(200, "添加成功");
        }
        return new ResponseResult<Void>(500, "添加失败");
    }

5. Create a SwaggerConfig configuration class

Add two methods in SwaggerConfig: (one of which is an auxiliary preparation for the other method)

The api() method uses @Bean , initializes at startup, and returns the instance Docket (Swagger API summary object). It should be noted here that the package path to be scanned is .apis(RequestHandlerSelectors.basePackage("xxx.yyy.zzz"))specified . Only the Controller class under this path will automatically generate the Swagger API document .

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;

/**
 * Swagger配置类
 */
@Configuration  //项目启动时加载此类
public class SwaggerConfig {
    
    
    @Bean
    public Docket api(){
    
    
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                // 此处自行修改为自己的 Controller 包路径。
                .apis(RequestHandlerSelectors.basePackage("com.lps.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    public ApiInfo apiInfo(){
    
    
        return new ApiInfoBuilder()
                .title("阿水的项目接口文挡")
                .description("阿水的 Project Swagger2 UserService Interface")  //说明信息
                .termsOfServiceUrl("http://localhost:8080/swagger-ui/index.html") //文档生成的主页地址
                .version("1.0")  //文档版本
                .build();
    }
}

The configuration of the apiInfo() method is relatively important. The basic information displayed on the main configuration page includes title, description, version, terms of service, etc. If you check the source code of the ApiInfo class, you will find more configurations such as license support

Four, spring security integration swagger

4.1, configure the release address

  http.authorizeRequests().antMatchers( "/swagger-ui.html",
                "/swagger-ui/*",
                "/swagger-resources/**",
                "/v2/api-docs",
                "/v3/api-docs",
                "/webjars/**").permitAll()
                .anyRequest().authenticated();

4.2, replace the UI

The whole process above has been completed, but many people don’t like the pages of the generated interface documents, and feel that they don’t conform to the usage habits of Chinese people, so some masters have provided other UI test pages. The use of this page is quite extensive.

Import the following dependencies and restart the project to access the address: http://localhost:8080/doc.html

	<dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>swagger-bootstrap-ui</artifactId>
        <version>1.9.6</version>
    </dependency>

[External link image transfer...(img-gaTrz5Yf-1681180965657)]

[External link image transfer...(img-JECwaVpz-1681180965657)]

Guess you like

Origin blog.csdn.net/lps12345666/article/details/130078422