A list,

In the current technology trend of front-end and back-end separation, front-end engineers over-rely on back-end engineers’ interfaces and data, which brings two major problems to development:

  • Problem 1. It is difficult to view the back-end interface: How to call it? How are parameters passed? How many parameters are there? What do the parameters mean?
  • Problem two: it is difficult to return data: what if the data is not returned correctly or not enough? How can you manipulate data flexibly?

This is the trouble caused by the separation of the front and back ends of many companies. How to solve these problems?

A common solution to problem one: the back-end team maintains an online document together and changes the corresponding document every time the interface is changed, but inevitably it will be missed, with a lot of effort but mediocre results.

The general solution to problem 2 is to set up a Mock server and manually record rules interface by interface.

Is there an optimal solution to these two problems? The answer is “Swagger” and “Easy Mock.”

1.1 introduce Swagger

Swagger is the world’s most popular framework for automatic generation and testing of interface documents, supporting almost all development languages.

Swagger official website address: Swagger. IO /

1.2 Introduction to Easy Mock

Easy Mock is a persistent service that visualizes and quickly generates Mock data.

Easy Mock can import all Swagger interfaces in one click, saving the trouble of manual recording interfaces, and can perfectly adapt the code comments in Swagger, which is a great tool for development.

Easy Mock data is stored in the cloud and can be used to create team projects that can truly be developed from the front end to the back end.

Let’s take a look at how to integrate Swagger and Easy Mock into your project.

1.3 Development Environment

  • JDK 8
  • Spring Boot 2.0.4
  • Swagger 2.9.2
  • The IDEA of 2018.2

Swagger integration

Swagger introduced in this paper is based on the Spring Boot framework. Let’s see the specific implementation steps.

2.1 Adding a Dependency

Configure pom.xml and 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>
Copy the code

Among them:

  • Springfox-swagger2 for JSON API document generation;
  • Springfox-swagger – UI for document interface presentation.

For more versions visit:

Springfox-swagger2:mvnrepository.com/artifact/io…

Springfox-swagger-ui:mvnrepository.com/artifact/io…

2.2 registered Swagger

Create the Java class “SwaggerConfig. Java” in the root directory of the source code, which is the sibling of appliction. Java.

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(a) {
        ApiInfo apiInfo = new ApiInfo(
                "Spring Boot APIs"."Spring Boot + Swagger2"."1.0.0".null."Wang Lei's Blog"."Author: Wang Lei"."http://www.apigo.cn/");
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .select()
                .paths(regex("/api/.*"))
                .build()
                .apiInfo(apiInfo)
                .useDefaultResponseMessages(false);
        returndocket; }}Copy the code

“@conditionalonexpression” is the annotation of Spring. Whether the user instantiates this class is used to determine whether to enable Swagger (Swagger needs to be shielded in the production environment).

2.3 Swagger Disabled in production Environment

Swagger enabled or not is configured in the application.properties file as follows:

swagger.enable=true

If the value is disabled in production environment, set it to False.

2.4 Adding Comments to documents

After completing the above three steps, Spring Boot’s integration of Swagger has been completed, but the documentation is not friendly enough, such as the Chinese description of classes, interfaces and parameters, which need to be completed in the code.

The following code:

@RestController
@RequestMapping("/api/user")
@Api(tags = "User controller")
public class UserController {
    @ApiOperation(value = "Say hello", notes = "Test Method")
    @ApiImplicitParam(name = "name", value = "Name")
    @RequestMapping(value = "/sayhi", method = RequestMethod.POST)
    public String sayHi(String name) {
        return "Hello," + name;
    }

    @ApiOperation(value = "Get all users", notes = "Query paging data")
    @RequestMapping(value = "/getall", method = RequestMethod.POST)
    public String getAll(a) {
        return "All Users"; }}Copy the code

Write code to run projects, the browser input: http://localhost:8080/swagger-ui.html to check the effect of adding comments, the following figure:

The @API is used to describe classes, the @ApiOperation is used to describe methods, and the @ApiIMPLicitParam is used to describe parameters. See below for more notes.

Example source code download: github.com/vipstone/sp…

Swagger document annotation

Now we have a preliminary understanding of Swagger. This section focuses on the use of Swagger annotations.

The purpose of the Swagger annotation is to add comments to the interface.

3.1@ Api class annotations

@api: Used to describe a class with the following attributes:

  • Tags describe the purpose of a class
  • Value has no use for the display and can be left unset

Code examples:

@API (tags = “article interface “)

3.2 @ApiOperation Method comments

@apiOperation: The attribute used to describe a method is as follows:

  • Value method description
  • Notes Method Remarks

Code examples:

@apiOperation (value = “fetch all articles “, notes =” query pagination data “)

The effect is shown below:

3.3@ApiIMPLICITParams Parameter annotation

ApiImplicitParams: Describes multiple parameters

@APIIMPLICITParam: Describes a single parameter

The attributes are as follows:

  • The name parameter
  • Value Specifies the description of the parameter
  • Required Indicates whether the message is required
  • ParamType Stores the following parameters: Header, Query, Path (resuful interface), body, and form
  • DataType Parameter type
  • DefaultValue specifies the defaultValue

Code examples:

@apiIMPLICITParams ({@apiIMPLICITParam (name = “name”, value = “name”, Required = true, paramType = “form”), @apiIMPLICITParam (name = “age”, value = “age”, Required = true, paramType = “form”),})

The effect is shown below:

3.4 @APIModel Entity object description

@APIModel: Entity class name description, attributes are as follows:

  • Class descriptions with the description

@APIModelProperty: Field description with the following attributes:

  • Value Field Description

The following is an example:

@ApiModel(description= "Return response data")
public class RestMessage implements Serializable{
    @ApiModelProperty(value = "Success or failure?")
    private boolean success=true;
    @ApiModelProperty(value = "Return object")
    private Object data;
    @ApiModelProperty(value = "Error number")
    private Integer errCode;
    @ApiModelProperty(value = "Error message")
    private String message;
    /* getter/setter */
}
Copy the code

4. Use Easy Mock

Easy Mock is an online Mock server. You can register an account to use it and store data in the cloud. It is Easy to use and does not require any local configuration.

4.1 Registering an Account

Enter easy-mock.com/login to register an account

4.2 Configuring the Easy Mock Project

After entering the management page, click demo personal demo project (the default created can be used directly), as shown below:

Enter interface list, click Settings => Click Swagger Docs API and select Upload (local file Upload), as shown below:

4.3 Exporting Swagger Interfaces

Browser visit: http://localhost:8080/v2/api-docs to see all interfaces of the JSON format of the project, right click save as file, the following figure:

Continue with 4.2 and upload the JSON file you just saved to Easy Mock.

4.4 Updating Interfaces

After saving the JSON data, you return to the project Settings page and click “Sync Swagger” to see all the interfaces. The diagram below:

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

Click the interface details and you can see that Easy Mock perfectly recognizes Swagger annotation as well, as shown in the following figure:

4.5 Modifying Data

There is no problem with the interface call, and the next step is to modify the operation data. Click the modify button of the corresponding interface on the right, as shown below:

Enter the edit page, the data you are editing is the data that the interface will return, the data is in JSON format, and it is saved online in the cloud, there is no need to worry about data loss, as shown below:

After editing, click on the update interface directly. Note that there is also a preview button on the edit page. Click on the preview button to simulate the request.

Five, the summary

So far all the content has been demonstrated, we solve the problem of interface management and data operation caused by the separation of front and back ends. Simulated data automatically generated interface documentation, a key, let we no longer rely on the back-end, focus solely on the front of the business, such as the backend interface after finish, then it is ok to conduct joint debugging, so we are done with all the problems, and the flexible configuration that we can not influence the production environment, and pollution production environment can be set to disable the Swagger, And we didn’t even need Postman with the preview feature.

The resources

Swagger2 annotation explanation: blog.csdn.net/xiaojin21ce…