[Spring Boot] Building RESTful services - using Swagger to generate Web API documents

Generate Web API documentation using Swagger

High-quality API documentation is very important in the process of system development. This section introduces what is Swagger, how to integrate Swagger in the Spring Boot project to build RESTful API documents, and configure general parameters such as Token for Swagger.

1. What is Swagger

Swagger is a standardized and complete framework for generating, describing, invoking and visualizing RESTful-style Web services, and is a very popular API expression tool.

Common API documentation has the following problems:

1) Due to the large number of interfaces and complex details (different HTTP request types, HTTP header information, HTTP request content, etc. need to be considered), creating such a high-quality document is a very tedious task.

2) With the continuous change of requirements, the interface documents must be modified synchronously, and it is easy to have inconsistencies between the documents and the business. In order to solve these problems, Swagger came into being. It can automatically generate a complete RESTful API document and update it synchronously according to the modification of the background code. In this way, the workload of maintaining interface documents can be reduced, and the description content can be integrated into the implementation code, so that maintenance documents and code modification can be integrated, and the code logic and description documents can be updated synchronously. In addition, Swagger also provides a complete test page to debug the API, making API testing easy and simple.

2. Use Swagger to generate Web API documents

Integrating Swagger in the Spring Boot project is also very simple, just introduce springfox-swagger2 and springfox-swagger-ui dependencies into the project. Let's take the previous user management module interface as an example to feel the charm of Swagger.

Step 01 Configure Swagger dependencies.

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>3.0.0</version>
        </dependency>

In the above example, two dependency packages, springfox-swagger2 and springfox-swagger-ui, are introduced in the project pom.xml configuration file. Among them, swagger2 is the main document generation component, and swagger-ui is the page display component.

Step 02 Create a Swagger2 configuration class.

@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {
    
    
    @Bean
    public Docket createRestApi () {
    
    
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
    
    
        return new ApiInfoBuilder()
                .title("Spring boot中使用Swagger2构建RESTful APIs")
                .description("相关文章请关注:https://blog.csdn.net/weixin_45627039?spm=1000.2115.3001.5343")
                .termsOfServiceUrl("https://blog.csdn.net/weixin_45627039?spm=1000.2115.3001.5343")
                // .contact("架构师精进")
                .version("1.0")
                .build();
    }
    /**
     * swagger增加url映射
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    
    
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars");
    }
}

In the above example, we added two annotations @Configuration and @EnableSwagger2 to the SwaggerConfig class.

The @Configuration annotation tells Spring Boot to load the class configuration.

The @EnableSwagger2 annotation enables Swagger2 by configuring a Docket Bean to configure the mapping path and the location of the interface to be scanned.

apiInfo mainly configures the information of the Swagger2 document website, such as the title of the website, the description of the website, the protocol used, etc.

have to be aware of is:

1) basePackage can be configured in SwaggerConfig com.weiz.example01.controller, or in the starter ComponentScan.

2) The URL mapping address of Swagger needs to be configured in SwaggerConfig: /swagger-ui.html.

Step 03 Add document description content.

After the above configuration is completed, the content description needs to be added to the API. We directly add the corresponding interface content description in the UserController of the previous user management module, the code is as follows:

    @Api(tags = {
    
    "用户接口"})
    @RestController
    public class UserController {
    
    
            @ApiOperation(value="创建用户", notes="根据User对象创建用户")
            @PostMapping(value ="user")
            public JSONResult save(@RequestBody User user){
    
    
                System.out.println("用户创建成功:" + user.getName());
                return JSONResult.ok(201, "用户创建成功");
            }
            @ApiOperation(value="更新用户详细信息", notes="根据id来指定更新对象,并根据传过来的user信息来更新用户详细信息")
            @PutMapping(value = "user")
            public JSONResult update(@RequestBody User user) {
    
    
                System.out.println("用户修改成功:" + user.getName());
                return JSONResult.ok(203, "用户修改成功");
            }
            @ApiOperation(value="删除用户", notes="根据url的id来指定删除对象")
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType ="Long", paramType = "query")
            @DeleteMapping("user/{userId}")
            public JSONResult delete(@PathVariable String userId) {
    
    
                System.out.println("用户删除成功:" + userId);
                    return JSONResult.ok(204,"用户删除成功");
            }
    }

In the above example, the interface information description is mainly added for the interface in UserController, including the purpose of the interface, description of request parameters, etc.

1) @Api annotation: used to add instructions to the entire controller (Controller).

2) @ApiOperation annotation: used to add descriptions to each API method.

3) @ApiImplicitParams, @ApiImplicitParam annotations: used to add descriptions to parameters.

Step 04 View the generated API documentation.

After completing the above configuration and code modification, Swagger 2 is integrated into the Spring Boot project. Next, start the project, visit http://localhost:8080/swagger-ui.html in the browser, and Swagger will automatically build the interface description document, as shown in the figure.

insert image description here
Swagger automatically displays all the interface information of the user management module, including interface function description, calling method, request parameters, return data structure and other information.

On the Swagger page, we found that there is a button try it out on the right side of each interface description, click the try it out button to call the interface for testing. As shown in the figure, click the try it out button on the interface for obtaining personnel information, enter the request parameter "2001" of userId, and click the Execute button to send the request to the background for interface verification testing.

insert image description here

3. Add token parameter for Swagger

In many cases, when the client calls the API, it needs to carry common parameters in the HTTP request header, such as token parameters for authorization verification. But how does Swagger describe such parameters? Next, an example will be used to demonstrate how to add fixed request parameters to Swagger.

In fact, it is very simple, modify the Swagger2Config configuration class, and use ParameterBuilder to form request parameters. The specific sample code is as follows:

@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {
    
    
    @Bean
    public Docket createRestApi() {
    
    
        ParameterBuilder parameterBuilder = new ParameterBuilder();
        List<Parameter> parameters = new ArrayList<Parameter>();
        parameterBuilder.name("token").description("token令牌")
                .modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(parameters);
    }
    ...
}

In the above example, the token is added to the HTTP request header as a globally unified parameter through the ParameterBuilder class. All APIs of the system will add this parameter uniformly.

After the completion, restart the application and check the interface again. As shown in the figure, we can see that the interface parameters already support sending token request parameters.

insert image description here
All APIs in the personnel management module are uniformly added with token parameters, and Swagger will automatically add the token parameters to the HTTP request header when calling.

4. Swagger common annotations

Swagger provides a series of annotations to describe interface information, including interface description, request method, request parameters, return information, etc. Common annotations are shown in the table.

insert image description here
In actual projects, in addition to providing @ApiImplicitParams annotations to describe simple parameters, Swagger also provides @ApiModel and @ApiModelProperty annotations for object parameters, which are used to encapsulate objects as incoming parameters or return data.

@ApiModel is responsible for describing the information of the object

@ApiModelProperty is responsible for describing the relevant content of the properties in the object

The above are some annotations commonly used in projects. Using these annotations, you can build a clear API document.

Guess you like

Origin blog.csdn.net/weixin_45627039/article/details/132202264