Spring Boot integrates swagger2

In the previous article, we integrated the RESTful API project around Spring Boot. However, in our actual development, one of our RESTful APIs may serve multiple different developers or development teams, including but not limited to PC, Android, IOS, even the current Hongmeng OS, web development and so on. In order to reduce the cost of frequent communication with other teams during normal development, we generally choose to create a related document to record all interface details, which is the interface document we often use in actual development.

  • However, when we used interface documents for recording, we found that because there are many interfaces and their details are relatively complex, we need to consider HTTP requests in different scenarios, and even HTTP related header information, content, etc., and we are creating such an interface. Documentation is time-consuming and labor-intensive. Many times, our statistics are incomplete, and even errors may occur. This is because it is easy for errors to occur during manual statistics, which is normal.
  • And as time goes by, when we make changes to the system, we will inevitably make changes to the relevant interfaces. Anyone who has done development knows this. If we adjust the interface here and adjust the interface there, we need to modify the document, but we During the development process, I found that code and documentation are at two levels. Unless the boss has strict control, it will cause many problems.

At this time, we found that there happened to be a technology that could solve our problem, that is, Swagger2. It can be easily integrated into Spring Boot, and cooperates with the Spring MVC program to organize the powerful RESTful API document, which greatly reduces the time required. We create the workload of the document and further integrate the content into our implementation code, so that code modification and document maintenance are integrated, modified at the same time, and recorded at the same time, allowing us to modify the document description while modifying the code.

In addition, Swagger2 provides powerful page testing functions to debug each RESTful API. The specific effect is shown in the figure below.

Preparation

We need to have a RESTful API project implemented by Spring Boot. We have covered it in the previous article. If you have not been exposed to RESTful API, please refer to the previous article to learn more.

Spring Boot integrates Swagger 2

The first step is to add dependencies, as usual, which will not be described in detail here, as follows:

<dependencies>
    <!-- Spring Boot Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Springfox Swagger2 -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version> <!-- Please use the latest version -->
    </dependency>

    <!-- Springfox Swagger UI -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version> <!-- Please use the latest version -->
    </dependency>
</dependencies>

Step 2: Add a @EnableSwagger2Doc annotation to the Spring Boot startup class, as follows:

@EnableSwagger2Doc
@SpringBootApplication
public class Application {<!-- -->

    public static void main(String[] args) {<!-- -->
        SpringApplication.run(Application.class, args);
    }
}

The third step is to create a User entity object and add Swagger2’s own interface to the relevant entity. Add @ApiModel to the entity class and @ApiModelProperty to the specific properties. on, used to describe specific attributes

@ApiModel(description="User Entity")
public class User {<!-- -->

    @ApiModelProperty("User ID")
    private Long id;
    @ApiModelProperty("User Name")
    private String name;
    @ApiModelProperty("User age")
    private Integer age;

    public Long getId() {<!-- -->
        return id;
    }

    public void setId(Long id) {<!-- -->
        this.id = id;
    }

    public String getName() {<!-- -->
        return name;
    }

    public void setName(String name) {<!-- -->
        this.name = name;
    }

    public Integer getAge() {<!-- -->
        return age;
    }

    public void setAge(Integer age) {<!-- -->
        this.age = age;
    }
}

The fourth step is to configure the relevant properties of Swagger2 in the application.properties file.

swagger.title=spring-boot-starter-swagger
swagger.description=Starter for swagger 2.x
swagger.version=1.9.0.RELEASE
swagger.license=Apache License, Version 2.0
swagger.licenseUrl=https://www.apache.org/licenses/LICENSE-2.0.html
swagger.termsOfServiceUrl=https://github.com/dyc87112/spring-boot-starter-swagger
swagger.contact.name=miaow
swagger.contact.url=https://luoxiaohei520.github.io
[email protected]
swagger.base-package=com.miaow
swagger.base-path=/**

The relevant meanings of the parameters are as follows:

swagger.title: title
swagger.description: Description
swagger.version: version
swagger.license: License
swagger.licenseUrl: License URL
swagger.termsOfServiceUrl: Terms of Service URL
swagger.contact.name: maintainer
swagger.contact.url: maintainer URL
swagger.contact.email: maintainer email
swagger.base-package: The base package for swagger scanning, default: full scan
swagger.base-path: The base URL rule that needs to be processed, default: /**

For more configuration, please refer to the official documentation

Start the project at this time and visit the link: http://localhost:8080/swagger-ui.html
I found that the pages were all in English.

In the fifth step, we will annotate the API related objects and methods of the Controller layer. In the fourth step, we found that when accessed through the browser, the entire interface is generated in English or follows the name defined by the code, which is not user-friendly. So we add descriptions to the API through relevant annotations: @Api, @ApiOperation annotations to add descriptions to the API, through @ApiImplicitParam, @ApiModel, @ApiModelProperty annotations are used to add descriptions to parameters.

@Api(tags = "User Management")
@RestController
@RequestMapping(value = "/users") // Through this configuration, the following mappings are all under /users
public class UserController {<!-- -->

    //Create a thread-safe Map to simulate the storage of users information
    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<>());

    @GetMapping("/")
    @ApiOperation(value = "Get user list")
    public List<User> getUserList() {<!-- -->
        List<User> r = new ArrayList<>(users.values());
        return r;
    }

    @PostMapping("/")
    @ApiOperation(value = "Create user", notes = "Create user based on User object")
    public String postUser(@RequestBody User user) {<!-- -->
        users.put(user.getId(), user);
        return "success";
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "Get user details", notes = "Get user details based on the id of the url")
    public User getUser(@PathVariable Long id) {<!-- -->
        return users.get(id);
    }

    @PutMapping("/{id}")
    @ApiImplicitParam(paramType = "path", dataType = "Long", name = "id", value = "User ID", required = true, example = "1")
    @ApiOperation(value = "Update user details", notes = "Specify the update object based on the id of the URL, and update the user details based on the passed user information")
    public String putUser(@PathVariable Long id, @RequestBody User user) {<!-- -->
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id, u);
        return "success";
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "Delete user", notes = "Specify the deletion object based on the id of the URL")
    public String deleteUser(@PathVariable Long id) {<!-- -->
        users.remove(id);
        return "success";
    }
}

Then access it through: http://localhost:8080/swagger-ui.html, click on the relevant information, and you can see the specific parameters and related attributes.
You can also test with relevant tips:


In the page requested in the above picture, we see that the user’s Value is an input box. Yes, in addition to viewing the interface function, Swagger also provides debugging and testing functions. We can click on the Model Schema on the right side of the picture above (yellow area: It specifies the data structure of User). At this time, there is a template of the user object in Value. We only need to make slight modifications and click the “Try it out!” button below to complete a request call!

At this time, you can also verify whether the previous POST request is correct through several GET requests.