自动生成接口文档操作手册

发布时间 2023-11-25 11:09:12作者: Ba11ooner

API 文档自动化生成

版本说明

实测仅适用于 Spring 2.x 版本,Spring 3 需要额外配置

后端

创建一个 Spring Web 项目

项目初始化
  • src
    • main
      • java
        • com.example
          • config
            • Knife4jConfig.java
          • entity
            • Entity.java
          • controller
            • EntityController.java
          • Application.java
      • resource
        • application.yaml
项目依赖
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <optional>true</optional>
</dependency>
Entity
@Data
@AllArgsConstructor
public class Entity {
    private int id;
    private String name;
}
EntityController
@RestController
@RequestMapping("/entity")
public class EntityController {
    @GetMapping("/get")
    public Entity getEntity() {
        Entity entity = new Entity(1, "Ba11ooner");
        return entity;
    }
}
API 文档生成插件
插件依赖
<dependency>
  <groupId>com.github.xiaoymin</groupId>
  <artifactId>knife4j-spring-boot-starter</artifactId>
  <version>3.0.3</version>
</dependency>
Knife4jConfig
@Configuration
@EnableSwagger2
@Profile("dev")
public class Knife4jConfig {
    @Bean
    public Docket defaultApi2() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        //TODO 配置项目信息
                        .title("project-backend")
                        .description("project-backend")
                        .version("1.0")
                        .build())
                .select()
                //TODO 指定 Controller 扫描包路径
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                .paths(PathSelectors.any())
                .build();
    }
}
Application
@SpringBootApplication
@Import(Knife4jConfig.class)
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(ApiDocGeneratorBackendApplication.class, args);
	}

}
application.yaml
spring:
  #swagger 兼容性配置
  mvc:
    pathmatch:
      matching-strategy: ANT_PATH_MATCHER

前端

参考文档

项目初始化

创建一个 Vue 项目(仅以 Vue 为例,其他同理)

API 文档生成插件
依赖下载
cnpm i @umijs/openapi ts-node -D
cnpm i umi-request
生成脚本编写

根目录创建 openapi.config.ts

declare let require: any
const { generateService } = require('@umijs/openapi')

generateService({
    requestLibPath: "import { request } from 'umi'",
    schemaPath:'http://localhost:8080/v3/api-docs',
    serversPath: './src/servers',
})
生成脚本的配置与执行

配置 package 脚本

"scripts": {
  "openapi": "ts-node openapi.config.ts"
},
npm openapi
修改脚本编写

批量修改生成的文本,在根目录下创建文件 openapi.replace.bat or openapi.replace.sh

  • Windows:bat 实现批处理

    @echo off
    chcp 65001 > nul
    
    setlocal enabledelayedexpansion
    
    set "old_text=import { request } from 'umi';"
    set "new_text=import request from 'umi-request';"
    
    set "file_pattern=src/servers/api/*.ts"
    
    for %%f in (%file_pattern%) do (
        set "old_file=%%~nf%%~xf"
        set "new_file=%%~nf_output%%~xf"
    
        set "input_file=src/servers/api/%%~nf%%~xf"
        set "output_file=src/servers/api/%%~nf_output%%~xf"
    
        (for /f "usebackq delims=" %%a in (!input_file!) do (
            set "line=%%a"
            set "line=!line:%old_text%=%new_text%!"
            echo(!line!
        )) > !output_file!
    
        (for /f "usebackq delims=" %%a in (!output_file!) do (
            set "line=%%a"
            set "line=!line!"
            echo(!line!
        )) > !input_file!
    
        del "%cd%\src\servers\api\%%~nf_output%%~xf"
    )
    
  • Unix:shell 实现批处理

    #!/bin/bash
    
    old_text="import { request } from 'umi';"
    new_text="import request from 'umi-request';"
    file_pattern="src/servers/api/*.ts"
    
    for file in $file_pattern; do
        old_file=$(basename "$file")
        new_file="${old_file%.*}_output.${old_file##*.}"
    
        input_file="src/servers/api/$old_file"
        output_file="src/servers/api/$new_file"
    
        sed -e "s/$old_text/$new_text/g" "$input_file" > "$output_file"
        mv "$output_file" "$input_file"
    done
    
    sh openapi.replace.sh
    
修改脚本的配置和执行
{
  "scripts": {
    "openapi-create": "ts-node openapi.config.ts",
    "openapi-replace": "openapi.replace.bat",
    "openapi": "npm run openapi-create && npm run openapi-replace"
  }
}
npm run openapi