Swagger-introduction and use of Swagger annotations

table of Contents

Swagger introduction

introduction

I believe that both front-end and back-end development have been more or less tortured by interface documents. 前端经常抱怨后端给的接口文档与实际情况不一致。后端又觉得编写及维护接口文档会耗费不少精力,经常来不及更新。其实无论是前端调用后端,还是后端调用后端,都期望有一个好的接口文档. However, for programmers, this interface document is just like comments. They often complain that the code written by others is not commented. However, when you write the code yourself, the most annoying thing is to write comments. Therefore, it is not enough to regulate everyone only through enforcement. As time goes by, version iterations and interface documentation often fail to keep up with the code.

1. What is Swagger

Find a solution if you find a pain point. When more people use the solution, it becomes a standard specification. This is the origin of Swagger. Through this set of specifications, you only need to define interfaces and interface-related information in accordance with its specifications. Then through a series of projects and tools derived from Swagger, you can generate interface documents in various formats, generate client and server code in multiple languages, and online interface debugging pages, etc. In this way, if you follow the new development model, when you develop a new version or iterative version, you only need to update the Swagger description file, and you can automatically generate interface documents and client-side server-side code to achieve call-side code, server-side code, and interface Document consistency.

But even so, for many developers, writing this description file in yml or json format is itself a certain burden, especially in the subsequent iterative development, often ignore updating this description file and directly change the code. Over time, this description file has drifted away from the actual project, and the interface document generated based on the description file has lost its reference significance. So Spring, as the unifying framework for the Java server, quickly incorporated the Swagger specification into its own standards, established the Spring-swagger project, and later changed it to the current Springfox. By introducing Springfox into the project, you can scan the relevant code, generate the description file, and then generate interface documents and client code consistent with the code . This form of generating interface documents through code is particularly important and efficient in subsequent projects that require continuous iteration.

Insert picture description here

  • Summary: Swagger is a tool used to define interface standards and interface specifications, and at the same time can automatically generate interface documentation based on your code

2. Officially provided tools

Insert picture description here

Swagger Codegen : Through Codegen, description files can be generated in html format and cwiki format interface documents, and at the same time, server and client codes in multiple languages ​​can be generated. Support localized execution and generation through jar package, docker, node, etc. It can also be generated online in the following Swagger Editor.

Swagger UI : Provides a visual UI page display description file. Interface callers, testers, project managers, etc. can all check related interfaces and make some simple interface requests on this page. The project supports online import of description files and local deployment of UI projects.

Swagger Editor : An editor for editing Swagger description files similar to the markendown editor. The editor supports real-time preview of the update effect of the description file. There are also two ways of online editor and local deployment editor.

Swagger Inspector : It feels similar to postman. It is an online version of postman that can test interfaces. Compared to making interface requests in Swagger UI, more information will be returned, and the actual request parameters and other data you requested will also be saved.

Swagger Hub : Integrates the functions of all the above projects. You can upload your description files to Swagger Hub in units of projects and versions. You can complete all the work of the above project in Swagger Hub, you need to register an account, divided into free version and paid version.

Springfox Swagger : Spring is based on the swagger specification and can automatically generate a description file in JSON format based on the project code of the SpringMVC and Spring Boot project. It is not provided by Swagger's official website. I will list it here as an explanation to facilitate the use of it later.

3. Build Swagger and SpringBoot environment

3.1 Introducing 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.2 Writing Swagger configuration class

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    
    
    @Bean
    public Docket createRestApi() {
    
    
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.baizhi.controller"))
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()
                        .title("SpringBoot整合Swagger")
                        .description("SpringBoot整合Swagger,详细信息......")
                        .version("9.0")
                        .contact(new Contact("xiaochen","www.baizhiedu.xin","[email protected]"))
                        .license("The Baizhi License")
                        .licenseUrl("http://www.baizhiedu.com")
                        .build());
    }
}

Insert picture description here

3.3 Start the springboot application

Insert picture description here

3.4 Access to Swagger's UI interface

  • Visit the ui interface provided by Swagger: http://localhost:8080/swagger-ui.html

Insert picture description here


4. Build with Swagger

1. Develop Controller interface

@RestController
@RequestMapping("user")
public class UserController {
    
    
    @GetMapping("findAll")
    public Map<String,Object> findAll(){
    
    
        HashMap<String, Object> map = new HashMap<>();
        map.put("msg","查询所有成功");
        map.put("state",true);
        return map;
    }   
}

Insert picture description here

2. Restart the project access interface interface

Insert picture description here

5.Swagger's annotations

5.1 @Api

  • Role: Used to specify the description text of the interface

  • Modification range: used on classes

    @RequestMapping("user")
    @Api(tags = "用户模块接口规范说明")
    public class UserController {
          
          
    	....
    }
    

5.2 @ApiOperation

  • Role: Used to describe specific methods in the interface

  • Modification range: used in method

    @GetMapping("findAll")
    @ApiOperation(value = "查询所有用户接口",
                  notes = "<span style='color:red;'>描述:</span>&nbsp;用来查询所有用户信息的接口")
    public Map<String,Object> findAll(){
          
          
      Map<String, Object> map = new HashMap<String,Object>();
      map.put("success","查询所有成功!");
      map.put("state",true);
      return map;
    }
    

    value: used to describe the interface

    notes: used to describe the interface in detail

5.3 @ApiImplicitParams

  • Function: Used to explain the parameters of the interface

  • Modification range: used in method

    @ApiImplicitParams({
          
          
      @ApiImplicitParam(name="id",value = "用户id",dataType = "String",defaultValue = "21"),
      @ApiImplicitParam(name="name",value = "用户姓名",dataType ="String",defaultValue = "张三")
    })
    public Map<String, Object> save(String id, String name) {
          
          
      .....
    }
    

5.4 @ApiResponses

  • Role: used in the request method, representing a set of responses

  • Modification range: used in method

    @ApiResponses({
          
          
                @ApiResponse(code = 400, message = "请求参数没填好"),
                @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
    })
    public Map<String, Object> save(String id, String name) {
          
          
      .....
    }
    

Guess you like

Origin blog.csdn.net/m0_37989980/article/details/107393030