How Spring Boot implements automatic generation of interface documents

How Spring Boot implements automatic generation of interface documents

When developing web applications, interface documentation is a very important part. It can help us quickly understand the functions and usage of APIs, and it is also an important tool for collaborating with other developers and teams. However, manually writing and maintaining interface documentation is tedious work, prone to omissions and errors. To this end, we can use some tools and frameworks provided by Spring Boot to automatically generate interface documents to improve development efficiency and document quality.

insert image description here

Introduction to Swagger

Swagger is a RESTful API document generation tool that can automatically generate interface documents, API tests, and client codes. It marks API information through annotations, and then generates API documentation and test pages based on the information. Swagger supports multiple languages ​​and frameworks, including Java and Spring Boot. In this article, we will introduce how to use Swagger to realize automatic generation of Spring Boot interface documents.

Integrate Swagger

add dependencies

First, we need to add Swagger dependencies to the Spring Boot project. Add the following dependencies in the pom.xml file:

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

Among them, springfox-swagger2 is the core dependency of Swagger, and springfox-swagger-ui is the UI component of Swagger, which is used to display interface documents and test pages.

Configure Swagger

After adding the dependencies of Swagger, we need to configure the relevant information of Swagger. In the configuration class of the Spring Boot application, we can use the @EnableSwagger2 annotation to enable Swagger, and use the @Configuration annotation to specify the configuration class. The specific code is as follows:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    
    
   @Bean
   public Docket api() {
    
    
       return new Docket(DocumentationType.SWAGGER_2)
               .select()
               .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
               .paths(PathSelectors.any())
               .build()
               .apiInfo(apiInfo());
   }

   private ApiInfo apiInfo() {
    
    
       return new ApiInfoBuilder()
               .title("Spring Boot接口文档")
               .description("Spring Boot接口文档")
               .version("1.0.0")
               .build();
   }
}

In the above code, we created a configuration class called SwaggerConfig and enabled Swagger with @EnableSwagger2 annotation. In the api method, we use the Docket object to configure Swagger-related information, including scanned API packages, API paths, and document information. Among them, RequestHandlerSelectors.basePackage specifies the API package to scan, and PathSelectors.any specifies to scan all API paths. In the apiInfo method, we use the ApiInfoBuilder object to configure information such as the title, description, and version number of the document.

Tag API information

After configuring Swagger, we need to add Swagger annotations to API methods to mark API information. The following are commonly used Swagger annotations:

  • @Api: Information used to mark the API, including the name, description and version number of the API.
  • @ApiOperation: Information used to mark API methods, including method names, descriptions, and HTTP methods.
  • @ApiParam: Used to mark the parameter information of the API method, including the name, description and data type of the parameter.
  • @ApiResponse: Used to mark the response information of the API method, including the response HTTP status code, description and response data type, etc.
  • @ApiModel: Used to mark the data model information of the API, including the name, description and field information of the data model.
  • @ApiModelProperty: Used to mark the field information of the API data model, including the name, description and data type of the field.

Here is an example using Swagger annotations:

@RestController
@RequestMapping("/users")
@Api(value = "用户管理", tags = "用户管理API")
public class UserController {
    
    
   @Autowired
   private UserService userService;

   @GetMapping("")
   @ApiOperation(value = "获取所有用户", notes = "获取所有用户的信息")
   public List<User> getUsers() {
    
    
       return userService.getUsers();
   }

   @GetMapping("/{id}")
   @ApiOperation(value = "获取用户信息", notes = "根据ID获取用户的信息")
   public User getUserById(@PathVariable("id") long id) {
    
    
       return userService.getUserById(id);
   }

   @PostMapping("")
   @ApiOperation(value = "创建用户", notes = "创建一个新的用户")
   public User createUser(@RequestBody User user) {
    
    
       return userService.createUser(user);
   }

   @PutMapping("/{id}")
   @ApiOperation(value = "更新用户信息", notes = "根据ID更新用户的信息")
   public User updateUser(@PathVariable("id") long id, @RequestBody User user) {
    
    
       return userService.updateUser(id, user);
   }

   @DeleteMapping("/{id}")
   @ApiOperation(value = "删除用户", notes = "根据ID删除用户")
   public void deleteUser(@PathVariable("id") long id) {
    
    
       userService.deleteUser(id);
   }
}

In the above code, we used the @Api annotation to mark the information of the API, including the name and description of the API. On each API method, we use the @ApiOperation annotation to mark the information of the method, including the name of the method, HTTP method and method description, etc. On the parameter, we use the @ApiParam annotation to mark the information of the parameter, including the name, description and data type of the parameter. On the return value, we use the @ApiResponse annotation to mark the response information, including the HTTP status code of the response, the description of the response, and the type of response data.

Access Interface Documentation

After completing the above steps, we can start the Spring Boot application and visit http://localhost:8080/swagger-ui.html to see the interface documents and test pages generated by Swagger. On the documentation page, we can view detailed information such as API information, parameters, and responses, and also perform interface tests. In the test page, we can select information such as HTTP method, input parameters, and request header, and then send a request and view the returned result.

Swagger common configuration

In addition to the above basic configuration, Swagger also provides many other configuration options to meet different needs. Here are some commonly used Swagger configuration options:

configuration group

In actual development, an application may contain multiple API groups, and each group corresponds to a different functional module or business scenario. In order to facilitate the management and search of APIs, we can use the grouping function of Swagger to display APIs in groups. In the configuration class, we can use the groupName method of Docket to specify the group name of the API. The specific code is as follows:

@Bean
public Docket api() {
    
    
    return new Docket(DocumentationType.SWAGGER_2)
        .groupName("users")
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
        .paths(PathSelectors.any())
        .build()
        .apiInfo(apiInfo());
}

In the above code, we use the groupName method to specify the group name of the API as "users".

Configure global parameters

In actual development, we may use some global parameters in the request header, path parameters or request body, such as authentication information, API version number, etc. In order not to add these parameters repeatedly in each API method, we can use Swagger's global parameter function to add these parameters to the API documentation. In the configuration class, we can use the globalOperationParameters method of Docket to specify global parameters. The specific code is as follows:

@Bean
public Docket api() {
    
    
    List<Parameter> parameters = new ArrayList<>();
    parameters.add(new ParameterBuilder()
        .name("Authorization")
        .description("认证信息")
        .modelRef(new ModelRef("string"))
        .parameterType("header")
        .required(false)
        .build());
    parameters.add(new ParameterBuilder()
        .name("version")
        .description("API版本号")
        .modelRef(new ModelRef("string"))
        .parameterType("query")
        .required(false)
        .build());

    return new Docket(DocumentationType.SWAGGER_2)
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
        .paths(PathSelectors.any())
        .build()
        .globalOperationParameters(parameters)
        .apiInfo(apiInfo());
}

In the above code, we use the globalOperationParameters method to add two global parameters, namely Authorization and version. Among them, ParameterBuilder is used to create parameter objects, name specifies the parameter name, description specifies the parameter description, modelRef specifies the parameter type, and parameterType specifies the parameter position. In Docket's globalOperationParameters method, we pass the parameter list to Swagger and add it to the API documentation.

Configure document styles

By default, the document style generated by Swagger may not be consistent with our project style. We can modify the appearance of the document by customizing the style file. In a Spring Boot application, we can create a public directory and create a swagger-ui.html file and a swagger.css file in it. In the swagger-ui.html file, we can introduce custom style files and override the default styles. The specific code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Swagger UI</title>
    <link rel="stylesheet" type="text/css" href="swagger.css">
    <linkrel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.10.0/swagger-ui.css" >
</head>
<body>
<div id="swagger-ui"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.10.0/swagger-ui-bundle.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.10.0/swagger-ui-standalone-preset.js"></script>
<script>
    window.onload = function() {
      
      
        const ui = SwaggerUIBundle({
      
      
            url: "/v2/api-docs",
            dom_id: '#swagger-ui',
            presets: [
                SwaggerUIBundle.presets.apis,
                SwaggerUIStandalonePreset
            ],
            layout: "BaseLayout",
            deepLinking: true,
            showExtensions: true,
            showCommonExtensions: true,
            docExpansion: "none"
        })
    }
</script>
</body>
</html>

In the above code, we introduced the custom style file swagger.css and the official style file swagger-ui.css provided by Swagger in the head tag. In the body tag, we created a div with an id of swagger-ui, and introduced the Swagger JavaScript file in it. In JavaScript, we use the SwaggerUIBundle object to create an instance of Swagger UI, and set the url property to "/v2/api-docs", indicating the URL address of the API documentation. The dom_id attribute specifies the rendering position of the Swagger UI, the presets attribute specifies the preset template used, the layout attribute specifies the layout of the document, the deepLinking attribute specifies whether to use deep links, and the showExtensions and showCommonExtensions attributes specify whether to display extended attributes. In a custom style file, we can use CSS rules to modify the appearance of the document, such as modifying the font size, color and background.

Summarize

This article describes how to use Swagger to automatically generate Spring Boot interface documents. We first added the dependency of Swagger and enabled Swagger in the configuration class. Then, we use annotations to mark API information and access interface documentation and test pages. In addition, we also introduced common configuration options of Swagger, including configuration grouping, global parameters and document styles, etc. Using Swagger can greatly improve development efficiency and document quality, and help us better manage and maintain API documents.

Guess you like

Origin blog.csdn.net/it_xushixiong/article/details/130975762