SpringBoot-Swagger2 integration and usage tutorial (generating API interface documentation)

SpringBoot-Swagger2 integration and usage tutorial (generating API interface documentation)

 

    In front-end and back-end development, in order to reduce the cost of communication with other teams, a RESTful API document is generally constructed to describe all interface information. However, the traditional method has many drawbacks, not only the workload of writing documents is huge, but also the maintenance is inconvenient and the test is inconvenient (need to use third-party tools, such as Postman to test)

    In order to solve these problems, we can use Swagger 2 to build online interface documents. The following examples demonstrate.

 

1. Basic introduction

1. What is Swagger 2

    Swagger 2 is an open source software framework that can help developers design, build, record, and use RESTful Web services. It integrates code and documentation, which can perfectly solve the problems of cumbersome documentation and inconvenient maintenance. Allows developers to concentrate most of their energy on the business, rather than cumbersome and trivial documents.

 

2. Installation and configuration

(1) First edit the pom.xml file of the project and add Swagger 2 related dependencies: 

Note: Because the swagger ui I introduced here is a version above 2.7, I also need to introduce guava, otherwise it will cause the project startup error (cannot start) due to guava compatibility issues

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<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>

<dependency>

    <groupId>com.google.guava</groupId>

    <artifactId>guava</artifactId>

    <version>20.0</version>

</dependency>


(2) Then create the configuration class of Swagger 2, the code is as follows: Code description:

  • First, Swagger 2 is opened through the @EnableSwagger2 annotation, and then the most important thing is to configure a Docket.
  • Configure the location of the controller to be scanned through the apis method, and configure the path through the paths method.
  • Build basic information of the document in apiInfo, such as description, contact information, version, title, etc.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

@Configuration

@EnableSwagger2

public class SwaggerConfig {

    @Bean

    Docket docket() {

        return new Docket(DocumentationType.SWAGGER_2)

                .apiInfo(apiInfo())

                .select()

                .apis(RequestHandlerSelectors.basePackage("com.example.demo"))

                .paths(PathSelectors.any())

                .build();

    }

 

    private ApiInfo apiInfo() {

        return new ApiInfoBuilder()

                .title("API测试文档")

                .description("DEMO项目的接口测试文档")

                .termsOfServiceUrl("http://www.hangge.com")

                .version("1.0")

                .contact(new Contact("航歌",

                        "http://www.hangge.com",

                        "[email protected]"))

                .build();

    }

}

 

Two, use examples

1. Add comments

(1) First, we add the relevant @Api annotation on the Controller:

(1)@Api 注解标注在类上用来描述整个 Controller 信息。
(2)@ApiOperation 注解标注在方法上,用来描述一个方法的基本信息。
(3)@ApiImplicitParam 注解标注在方法上,用来描述方法的参数。其中 paramType 是指方法参数的类型,有如下可选值:

  • path:参数获取方式为 @PathVariable
  • query:参数获取方式为 @RequestParam
  • header:参数获取方式为 @RequestHeader
  • body
  • form

(4)如果有多个参数,可以将多个参数的 @ApiImplicitParam 注解放到 @ApiImplicitParams 中。
(5)@ApiResponse 是对响应结果的描述。code 表示响应码,message 为相应的描述信息。如果有多个 @ApiResponse,则放在一个 @ApiResponses 中。
(6)@ApiIgnore 注解表示不对某个接口生成文档。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

@RestController

@Api(tags = "用户数据接口")

public class UserController {

    @ApiOperation(value ="查询用户", notes = "根据 id 查询用户")

    @ApiImplicitParam(paramType = "path", name = "id", value = "用户 id", required = true)

    @GetMapping("/user/{id}")

    public String getUserById(@PathVariable Integer id){

        return "查找的用户id是:" + id;

    }

 

    @ApiOperation(value = "新增用户", notes = "根据传入的用户名和密码添加一个新用户")

    @ApiImplicitParams({

            @ApiImplicitParam(paramType = "query", name = "username",

                    value = "用户名", required = true, defaultValue = "test"),

            @ApiImplicitParam(paramType = "query", name = "password",

                    value = "密码", required = true, defaultValue = "123")

    })

    @PostMapping("/user")

    public String addUser(@RequestParam String username, @RequestParam String password) {

        return "新增用户:" + username + " " + password;

    }

 

    @ApiOperation(value = "删除用户", notes = "根据 id 删除用户")

    @ApiResponses({

            @ApiResponse(code = 200, message = "删除成功!"),

            @ApiResponse(code = 500, message = "删除失败!")

    })

    @DeleteMapping("/user/{id}")

    public Integer deleteUserById(@PathVariable Integer id) {

        return id;

    }

 

    @ApiOperation(value = "修改用户", notes = "传入用户信息进行更新修改")

    @PutMapping("/user")

    public String updateUser(@RequestBody User user){

        return user.toString();

    }

 

    @ApiIgnore

    @GetMapping("/user/test")

    public String test() {

        return "这是一个测试接口,不需要在api文档中显示。";

    }

}


(2)接着对模型对象也添加相关的注解:

    由于在上面 Controller 里的 updateUser 方法中,使用 @RequestBody 注解来接收数据,此时可以通过 @ApiModel 注解和 @ApiModelProperty 注解配置 User 对象的描述信息。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

@Getter

@Setter

@ToString

@ApiModel(value = "用户实体类", description = "用户信息描述类")

public class User {

    @ApiModelProperty(value = "用户id")

    private Integer id;

 

    @ApiModelProperty(value = "用户名")

    private String username;

 

    @ApiModelProperty(value = "用户密码")

    private String password;

}

 

2,查看接口文档

(1)启动 Spring Boot 项目,在浏览器中输入 http://localhost:8080/swagger-ui.html 即可看到接口文档。

原文:SpringBoot - Swagger2的集成与使用教程(生成API接口文档)

 

(2)展开任意一个接口描述,单击 Try it out 按钮后,可以实现对该接口的测试。

 

附:使用 swagger-bootstrap-ui 代替原来的 ui

(1)如果觉得原先使用的 swagger ui 比较丑、或者不方便的话,可以试试 swagger-bootstrap-ui。只需修改 pom.xml 文件,将原来的 springfox-swagger-ui 依赖替换成  swagger-bootstrap-ui 即可。

注意:1.9.6 是 swagger-bootstrap-ui 的最后一个版本。由于各种原因,原作者又另起一新的项目:knife4j-spring-ui。knife4j 会包含 swagger-bootstrap-ui 的所有特性,并增加许多新特性,有兴趣的小伙伴可以尝试一下。

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<dependency>

    <groupId>io.springfox</groupId>

    <artifactId>springfox-swagger2</artifactId>

    <version>2.9.2</version>

</dependency>

<dependency>

    <groupId>com.github.xiaoymin</groupId>

    <artifactId>swagger-bootstrap-ui</artifactId>

    <version>1.9.6</version>

</dependency>

<dependency>

    <groupId>com.google.guava</groupId>

    <artifactId>guava</artifactId>

    <version>20.0</version>

</dependency>


(2)项目启动后,通过 http://localhost:8080/doc.html 地址即可访问新的 UI 界面:

原文:SpringBoot - Swagger2的集成与使用教程(生成API接口文档)

 

(3)可以看到 bootstrap 风格的界面样式比原先的清爽、高效许多:

Guess you like

Origin blog.csdn.net/yucaifu1989/article/details/112429822