Spring boot (IX) swagger2 automatically generates interface documents and mock simulation data

1、 Introduction

Under the current technology trend of separating the front end from the back end, the front-end engineers rely too much on the interfaces and data of the back-end engineers, which brings two major problems to the development:

This is a problem caused by the separation of front and rear ends of many companies. How can we solve these problems?

General solution to problem 1: the back-end team jointly maintains an online document. Each time the interface is changed, the corresponding document will be changed, but it will inevitably be missed. It takes a lot of effort, but the effect is mediocre.

The general solution to problem 2: build a mock server by yourself, and then manually record rules one interface by one interface, or is it a laborious manual work.

Is there an optimal solution to solve the above two problems? The answer is yes, that is "swagger" and "easy mock".

1.1 swagger introduction

Swagger is the most popular framework for automatic generation and testing of interface documents in the world. It supports almost all development languages.

Swagger official website address: https://swagger.io/

1.2 introduction to easy mock

Easy mock is a visual and persistent service that can quickly generate simulated data.

Easy mock can import all interfaces of swagger with one click, which saves the trouble of manually recording interfaces, and can perfectly adapt the code comments in swagger. It can be described as a sharp tool for development.

Easy mock data is saved in the cloud, and team projects can be created, which can truly realize the project development from the front end to the back end.

Next, let's take a look at how to integrate swagger and easy mock in the project.

1.3 development environment

2、 Swagger integration

Swagger introduced in this article is based on the spring boot framework. Let's look at the specific implementation steps.

2.1 adding dependencies

Configure POM XML, add the following code:

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

Of which:

For more versions, visit:

springfox-swagger2: http://mvnrepository.com/artifact/io.springfox/springfox-swagger2

springfox-swagger-ui: http://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui

2.2 register swagger

In the root directory of the source code, that is, application Java, create a Java class "swaggerconfig. Java" (naming doesn't matter), and the code is as follows:

import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static springfox.documentation.builders.PathSelectors.regex;

@Configuration
@EnableSwagger2
@ConditionalOnExpression("${swagger.enable:true}")
public class SwaggerConfig  {
    @Bean
    public Docket swaggerSpringMvcPlugin() {
        ApiInfo apiInfo = new ApiInfo(
                "Spring Boot APIs","Spring Boot + Swagger2","1.0.0",null,"王磊的博客","作者:王磊","http://www.apigo.cn/");
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .select()
                .paths(regex("/api/.*"))
                .build()
                .apiInfo(apiInfo)
                .useDefaultResponseMessages(false);
        return docket;
    }
}

Where "@ conditionalonexpression" is the annotation of spring. Whether the user instantiates this class is used to judge whether swagger is enabled (swagger needs to be shielded in the production environment).

2.3 disable swagger in production environment

Whether to enable swagger is in application The configuration in the properties file is as follows:

If the production environment is disabled, set it to false.

2.4 adding document notes

After completing the above three steps, the integration of spring boot with swagger has been completed, but the documents are not friendly enough, such as the Chinese description of classes and interfaces and the description of parameters. They need to be completed in the code.

The following code:

@RestController
@RequestMapping("/api/user")
@Api(tags = "用户控制器")
public class UserController {
    @ApiOperation(value = "打招呼",notes = "测试方法")
    @ApiImplicitParam(name = "name",value = "姓名")
    @RequestMapping(value = "/sayhi",method = RequestMethod.POST)
    public String sayHi(String name) {
        return "Hello," + name;
    }

    @ApiOperation(value = "获取所有用户",notes = "查询分页数据")
    @RequestMapping(value = "/getall",method = RequestMethod.POST)
    public String getAll() {
        return "所有用户";
    }
}

After writing the code, run the project and enter in the browser: http://localhost:8080/swagger -ui. HTML to view the effect of adding comments, as shown in the following figure:

Where @ API is used to describe classes, @ apioperation is used to describe methods, and @ apiimplicitparam is used to describe parameters. See the following for more notes.

Sample source code download: https://github.com/vipstone/springboot-example/tree/master/springboot-swagger

3、 Swagger document annotation

Now that we have a preliminary understanding of swagger, this section focuses on the use of swagger annotations.

The swagger annotation is used to annotate interfaces.

3.1 @ API notes

@API: used to describe the properties of a class, as follows:

Code example:

3.2 @ apioperation method notes

@Apioperation: describes the properties of the method, as follows:

Code example:

The effect is as follows:

3.3 @ apiimplicitparams parameter notes

@Apiimplicitparams: describes multiple parameters

@Apiimplicitparam: describes a single parameter

The properties are as follows:

Code example:

The effect is as follows:

3.4 @ apimodel entity object description

@Apimodel: entity class name description, with the following attributes:

@Apimodelproperty: field description. The properties are as follows:

Examples are as follows:

@ApiModel(description= "返回响应数据")
public class RestMessage implements Serializable{
    @ApiModelProperty(value = "是否成功")
    private boolean success=true;
    @ApiModelProperty(value = "返回对象")
    private Object data;
    @ApiModelProperty(value = "错误编号")
    private Integer errCode;
    @ApiModelProperty(value = "错误信息")
    private String message;
    /* getter/setter */
}

4、 Easy mock use

Easy mock is an online mock server. It can be used by registering an account. The data is stored in the cloud. It is easy to use and does not need any local configuration. The specific operation steps are shown below.

4.1 registered account

Browser input: https://easy-mock.com/login Registered account

4.2 configure easy mock project

After entering the management page, click the demo personal demo project (which is created by default and can be used directly), as shown in the following figure:

Enter the interface list, click settings = > Click swagger docs API and select upload (local file upload), as shown below:

4.3 export swagger interface

Browser access: http://localhost:8080/v2/api -Docs will see all interfaces of the project in JSON format. Right click to save as a file, as shown in the following figure:

Continue the operation in 4.2 and upload the JSON file just saved to easy mock.

4.4 update interface

After saving the JSON data, you will return to the project settings page. At this time, click "synchronize swagger" to see all interfaces. As shown below:

Now that all interfaces have been imported, you can click the copy button on the right side of the interface list to call happily.

At this time, it can be completely separated from the back end. Click the interface details to see that easy mock perfectly recognizes swagger and notes are available, as shown in the following figure:

4.5 modifying data

There is no problem calling the interface. The next step is to modify the operation data. Click the Modify button of the corresponding interface on the right, as shown in the following figure:

After entering the edit page, the data you are editing is the data to be returned by the interface. The data is in JSON format and saved online in the cloud. There is no need to worry about data loss, as shown in the following figure:

After editing, you can directly click the update interface. Note that there is also a preview button on the editing page. Click it to simulate the request, which saves even postman. The effects are as follows:

5、 Summary

So far, all the contents have been demonstrated. We have solved the problems of difficult interface management and data operation caused by the separation of front and rear ends. Automatically generate interface documents and one click simulation data, so that we no longer rely on the back end and only focus on the business of the front end. After the back end writes the interface, we can conduct joint debugging. In this way, we can solve all problems without effort. Moreover, the flexible configuration allows us not to affect and pollute the production environment. The production environment can be set to disable swagger, And with the preview function, we even saved postman.

reference material

Swagger2 notes: https://blog.csdn.net/xiaojin21cen/article/details/78654652

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>