Home >Java >javaTutorial >How to use SpringBoot integrated interface management tool Swagger

How to use SpringBoot integrated interface management tool Swagger

王林
王林forward
2023-05-14 19:04:081739browse

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't see the source code or documents or can't pass network traffic detection. Ability to discover and understand the functionality of various services. When services are defined through Swagger, consumers can interact with remote services with a small amount of implementation logic.

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 document. Swagger will use the annotations marked in the project to mark the information. Generate corresponding API documentation. Swagger is known as the most popular API tool in the world. It provides a complete solution for API management. The factors that need to be considered for API document management are basically included. Here we will explain the most commonly used customization content.

1. Add swagger coordinates

Spring Boot integrates Swagger 3. It is very simple. You only 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. Swagger Helloword implementation

2.1. Create 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;
    }
}

How to use SpringBoot integrated interface management tool Swagger

2.3. Access address
http://localhost:8080/swagger-ui/index.html

How to use SpringBoot integrated interface management tool Swagger

##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 annotations and ApiOperation annotations

  • @Api

is used on the class to indicate that it is a swagger resource. @API has two attributes: value , 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. Each list displays all interfaces

value functions like tags, but cannot have multiple values

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

  • @ApiOperation

Used on methods to indicate the operation of an http request

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

Case: Use @Api and @ApiOperation to generate api documents

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 annotations and ApiImplicitParam

@ApiImplicitParams annotations and @ApiImplicitParam are used for non-object parameters (parameter binding) in methods Use when arriving at a simple type.) Explain

语法:
@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;
    }
}

How to use SpringBoot integrated interface management tool Swagger##3, ApiModel annotation and ApiModelProperty

    @ApiModel
  • is used on entity classes to describe the class and is used for parameter reception instructions in entity classes.

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

@ApiResponses annotation and @ApiResponse annotation are marked on the Controller method 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 the SwaggerConfig configuration class

Add two methods in SwaggerConfig: (one method is to make auxiliary preparations for the other method)

api() method uses @Bean, Initialized at startup, the instance Docket (Swagger API summary object) is returned. What needs to be noted here is that .apis(RequestHandlerSelectors.basePackage("xxx.yyy.zzz")) specifies the package path that needs to be scanned. Only the Controller under this path Classes will automatically generate Swagger API documentation.

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();
    }
}

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

4. Springsecurity integrates swagger

4.1, configures 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, replaces the UI

The entire process above has been completed, but the generated In fact, many people don't like the interface document page, and feel that it is not in line with the usage habits of Chinese people. Therefore, some experts have provided other UI test pages. The use of this page is quite extensive.

Import the following dependencies, restart the project and 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>

The above is the detailed content of How to use SpringBoot integrated interface management tool Swagger. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete