In the application development process often need to provide a RESTful API interface to other applications or client, especially in the version fast iterative development process, modify the interface at the same time also need to be synchronized to modify the corresponding interface documentation, which we always do the repetitive work, and if you forget to modify the interface documentation, it may cause unnecessary trouble.

To solve these problems, Swagger was born, so let’s take a quick look.

Introduction of Swagger

Swagger is a canonical and complete framework for generating, describing, invoking, and visualizing RESTful Web services.

The overall goal is for the client and file system to update at the same rate as the server. File methods, parameters, and models are tightly integrated into server-side code, allowing the API to always be synchronized.

Let’s integrate Swagger with Spring Boot to build a powerful interface document.

Spring Boot integrates Swagger

Spring Boot integrated Swagger is mainly divided into the following three steps:

  1. Add Swagger dependency
  2. Add Swagger document configuration
  3. Write API documentation using Swagger annotations

Join the rely on

First create a project and add the Swagger dependency to the project as follows:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> < the 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> The < version > 2.9.2 < / version > < / dependency >Copy the code

Join the configuration

Add @enablesWagger2 to the config class to indicate that Swagger is enabled. Inject a Docket class to configure some API information. The apiInfo() method defines several document messages as follows:

@Configuration
@EnableSwagger2
public class Swagger2Configuration {

    @Bean
    public Docket createRestApi() {
        returnNew Docket (DocumentationType SWAGGER_2). ApiInfo (apiInfo ()). The select () / / swagger document scanning package .apis(RequestHandlerSelectors.basePackage("com.wupx.interfacedoc.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Test Interface List")
                .description("Swagger2 interface Document")
                .version("v1.0.0")
                .contact(new Contact("wupx"."https://www.tianheyu.top"."[email protected]"))
                .license("Apache License, Version 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") .build(); }}Copy the code

Some documents are listed below:

  • Title: indicates the title of the interface document
  • Description: indicates the detailed description of the interface document
  • TermsOfServiceUrl: Generally used to store the address of the company
  • Version: indicates the version number of an API document
  • Contact: indicates the URL and email address of the maintenance owner
  • License: license
  • LicenseUrl: indicates the licenseUrl

Writing API documentation

Create a User entity class under the domain package and use the @APIModel annotation to indicate that this is an entity returned by Swagger. The @APIModelProperty annotation indicates several attributes of the entity as follows (getters/setters omitted) :

@ApiModel(value = "User", description = "User Entity Class")
public class User {

    @ApiModelProperty(value = "User id", hidden = true)
    private Long id;

    @ApiModelProperty(value = "User name")
    private String name;

    @ApiModelProperty(value = "User age")
    private String age;

    // getter/setter
}
Copy the code

Finally, create a UserController class under the Controller package that provides the user API (without using the database) as follows:

@RestController
@RequestMapping("/users")
@Api(tags = "User Management Interface")
public class UserController {

    Map<Long, User> users = Collections.synchronizedMap(new HashMap<>());

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

    @PostMapping("/")
    @ApiOperation(value = "Create user")
    public String addUser(@RequestBody User user) {
        users.put(user.getId(), user);
        return "success";
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "Get the user with the specified ID")
    @ApiImplicitParam(name = "id", value = "User id", paramType = "query", dataTypeClass = Long.class, defaultValue = "999", required = true)
    public User getUserById(@PathVariable Long id) {
        return users.get(id);
    }

    @PutMapping("/{id}")
    @ApiOperation(value = "Update users by ID")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "User id", defaultValue = "1"),
            @ApiImplicitParam(name = "name", value = "User name", defaultValue = "wupx"),
            @ApiImplicitParam(name = "age", value = "User age", defaultValue = "18")
    })
    public User updateUserById(@PathVariable Long id, @RequestParam String name, @RequestParam Integer age) {
        User user = users.get(id);
        user.setName(name);
        user.setAge(age);
        return user;
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "Delete user", notes = "Delete user by ID")
    @ApiImplicitParam(name = "id", value = "User id", dataTypeClass = Long.class, required = true)
    public String deleteUserById(@PathVariable Long id) {
        users.remove(id);
        return "success"; }}Copy the code

Start the project, visit http://localhost:8080/swagger-ui.html, you can see we define the document has been displayed on the Swagger page, as shown in the figure below:

At this point, we are done integrating Spring Boot with Swagger.

In addition to interface document functions, Swagger also provides interface debugging functions. For example, to create a user interface, click Create user interface, you can see parameters, return values and response codes defined by the interface. Click Try it out button, and then click Execute to initiate call requests and create users. As shown below:

Annotation is introduced

Since Swagger 2 provides a large number of annotations for development, here are some of the more common ones.

@Api

@Api is used in the interface document resource class to mark the document resource whose current class is Swagger. It contains several common attributes:

  • Value: defines the name of the current interface document.
  • Description: Describes the current interface document.
  • Tag: Documents can be defined by more than one name, but the value attribute is invalidated if there are both tag and value attributes.
  • Hidden: If the value is true, the document is hidden.

@ApiOperation

The @apiOperation method is used to annotate the interface. It contains several common attributes:

  • Value: Short description of the API.
  • Note: Details of the API.
  • Esponse: The return type of the interface (note: this is not the actual response, but the actual result of the object).
  • Hidden: If the value is true, it will be hidden in the document.

@ ApiResponse, @ ApiResponses

@apiresponses and @apiResponse are used together to return the HTTP status code. The value of @ApiResponses is a collection of @ApiResponse, multiple @ApiResponses are separated by commas, where @ApiResponse contains the following attributes:

  • Code: indicates the HTTP status code.
  • “Message” : indicates the HTTP status.
  • ResponseHeaders: indicates the HTTP response header.

@ApiParam

The @apiParam parameter used for the method, which contains the following common attributes:

  • Name: Parameter name.
  • Value: indicates the parameter value.
  • Required: If the value is true, it is a required field.
  • DefaultValue: indicates the defaultValue of the parameter.
  • Type: indicates the parameter type.
  • Hidden: If the value is true, this parameter is hidden.

@ ApiImplicitParam, @ ApiImplicitParams

A subset of @ApiIMPLicitParams is the @ApiIMPLicitParam annotation, where the @APIIMPLicitParam annotation contains the following parameters:

  • Name: Parameter name.
  • Value: indicates the parameter value.
  • Required: If the value is true, it is a required field.
  • DefaultValue: indicates the defaultValue of the parameter.
  • DataType: dataType.
  • Hidden: If the value is true, this parameter is hidden.
  • AllowMultiple: Whether duplicates are allowed.

@ResponseHeader

The responseHeaders of the API document. If you need to set the ResponseHeader, set @responseHeader to the responseHeaders parameter of @apiResponse. The @responseHeader provides the following parameters:

  • Name: indicates the name of the response header.
  • Description: Response header remarks.

@ApiModel

Sets the entity class of the API response to be used as the API return object. @apiModel provides the following parameters:

  • Value: indicates the entity class name.
  • Description: Description of the entity class.
  • SubTypes: subTypes.

@ApiModelProperty

Set the attributes of the API response entity, which contains the following parameters:

  • Name: indicates the attribute name.
  • Value: indicates the value of an attribute.
  • Notes: Comments for properties.
  • DataType: dataType.
  • Required: This field must be passed in if the value is true.
  • Hidden: If the value is true, this field is hidden.
  • ReadOnly: If true, the field is read-only.
  • AllowEmptyValue: Null values are allowed if true.

That concludes the main notes Swagger provides.

conclusion

Swagger can be easily integrated into Spring Boot to build a powerful RESTful API document, which can reduce our workload of writing interface documents. Meanwhile, the description of the interface is also integrated into the code, allowing us to modify the interface documentation conveniently while modifying the code logic. Swagger also provides page testing to debug each RESTful API.

If you haven’t used it in your project, try it and you’ll find it’s much more efficient.

The full code for this article is available at github.com/wupeixuan/S… In the interface-doc directory of

The best relationship is mutual achievement. The three links of watching, forwarding and leaving messages are the biggest motivation for my creation.

reference

swagger.io

Github.com/wupeixuan/S…

Spring Boot 2 Combat Tour