温馨提示×

如何在Linux上自定义Swagger文档

小樊
40
2025-10-03 06:45:52
栏目: 智能运维

一、准备工作:安装必要工具 在Linux系统上自定义Swagger文档前,需根据技术栈安装对应工具。若使用Node.js(Express/Koa),通过npm安装核心工具:

npm install swagger-jsdoc swagger-ui-express --save-dev  # 生成和展示Swagger文档

若使用Java(Spring Boot),添加Swagger依赖到pom.xml(Springfox)或build.gradle(SpringDoc OpenAPI):

<!-- SpringFox(Swagger 2) -->
<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>
// SpringDoc OpenAPI(推荐,支持OpenAPI 3)
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.5.0'

安装完成后,确保工具版本与项目技术栈兼容。

二、编写Swagger配置文件(定义文档结构) Swagger文档的核心是OpenAPI规范(YAML/JSON格式),需创建swagger.yamlswagger.json文件(推荐YAML,可读性更强)。以下是关键配置项:

  • 基础信息:标题、描述、版本、联系方式(用于标识文档归属);
  • 服务器配置:API的基准URL(如开发/生产环境切换);
  • 路径定义:API端点(/api/users)、HTTP方法(GET/POST)、参数(路径/查询/请求体)、响应(状态码、数据结构);
  • 组件定义:可复用的模型(如User对象)、参数、响应(减少重复配置)。

示例(YAML格式,适用于Spring Boot/Node.js)

openapi: 3.0.0
info:
  title: "用户管理API"
  description: "提供用户信息的增删改查接口"
  version: "1.0.0"
  contact:
    name: "开发团队"
    email: "dev@example.com"
servers:
  - url: "http://localhost:8080"  # 开发环境
    description: "本地开发服务器"
paths:
  /api/users:
    get:
      summary: "获取用户列表"
      description: "返回所有用户的简要信息"
      responses:
        '200':
          description: "成功返回用户列表"
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/User"
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
          description: "用户唯一ID"
        name:
          type: string
          description: "用户姓名"
      required:
        - id
        - name

配置文件需放在项目根目录或指定路径(如Spring Boot的src/main/resources)。

三、集成Swagger到应用(连接文档与代码)

1. Node.js(Express)集成

在Express应用中,通过swagger-ui-express中间件加载Swagger文档:

const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.yaml');  // 导入配置文件

const app = express();
const PORT = process.env.PORT || 3000;

// 集成Swagger UI(挂载到/api-docs路径)
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

// 示例API路由(需与swagger.yaml中的路径一致)
app.get('/api/users', (req, res) => {
  res.json([{ id: 1, name: '张三' }, { id: 2, name: '李四' }]);
});

app.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}`);
});

启动应用后,访问http://localhost:3000/api-docs即可查看Swagger UI界面。

2. Java(Spring Boot)集成

方式1:SpringFox(传统)

创建配置类,启用Swagger并配置扫描路径:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

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

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("用户管理API")
                .description("提供用户信息的增删改查接口")
                .version("1.0.0")
                .build();
    }
}

访问http://localhost:8080/swagger-ui.html查看文档。

方式2:SpringDoc OpenAPI(推荐)

无需额外配置类,只需添加依赖,Spring Boot会自动识别swagger.yaml文件。访问http://localhost:8080/swagger-ui/index.html即可查看文档。

四、自定义Swagger文档(优化可读性与功能)

1. 修改文档元数据

通过配置文件调整标题、描述、版本等信息,使文档更符合项目需求(如上述swagger.yaml中的info部分)。

2. 自定义UI外观

  • Node.js:通过swagger-ui-expresscustomCss选项引入自定义CSS:
    app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, {
      customCss: '.swagger-ui .topbar { background-color: #4CAF50; }'  // 修改顶部栏颜色
    }));
    
  • Java(SpringFox):通过Docket配置自定义CSS或Logo:
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .enableUrlTemplating(true)
                .uiConfiguration(uiConfig -> uiConfig
                        .deepLinking(true)
                        .displayOperationId(false)
                        .defaultModelsExpandDepth(3)
                        .defaultModelExpandDepth(3)
                        .defaultModelRendering(ModelRendering.EXAMPLE)
                        .displayRequestDuration(true)
                        .docExpansion(DocExpansion.NONE)
                        .filter(false)
                        .maxDisplayedTags(null)
                        .operationsSorter(OperationsSorter.ALPHA)
                        .showExtensions(false)
                        .tagsSorter(TagsSorter.ALPHA)
                        .supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS)
                )
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    
    或通过application.properties添加自定义Logo:
    springfox.documentation.swagger.v2.path=/swagger-resources/v2/api-docs
    springfox.documentation.swagger-ui.custom-css-url=/custom.css
    springfox.documentation.swagger-ui.logo-image=/logo.png
    

3. 隐藏敏感信息或无关接口

  • Java(SpringFox):使用@ApiIgnore注解隐藏特定接口或参数:
    @ApiIgnore
    @GetMapping("/admin/secret")
    public String secret() {
        return "This is a secret endpoint";
    }
    
  • Node.js:在swagger.yaml中通过x-hidden: true标记隐藏路径:
    /api/admin/secret:
      x-hidden: true  # 不显示在Swagger UI中
      get:
        summary: "敏感接口"
        responses:
          '200':
            description: "隐藏的接口内容"
    

4. 添加详细注释与示例

在代码中使用Swagger注解(Java)或YAML描述(Node.js),丰富接口信息:

  • Java(SpringFox)
    @ApiOperation(value = "获取用户信息", notes = "根据用户ID获取详细信息,需管理员权限")
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "成功获取用户信息", response = User.class),
        @ApiResponse(code = 404, message = "用户不存在")
    })
    @GetMapping("/api/users/{id}")
    public ResponseEntity<User> getUser(@ApiParam(value = "用户ID", required = true, example = "1") @PathVariable Integer id) {
        // 实现逻辑
    }
    
  • Node.js(YAML)
    /api/users/{id}:
      get:
        summary: "获取用户信息"
        description: "根据用户ID获取详细信息,需管理员权限"
        parameters:
          - in: path
            name: id
            required: true
            schema:
              type: integer
            description: "用户唯一ID"
        responses:
          '200':
            description: "成功获取用户信息"
            content:
              application/json:
                schema:
                  $ref: "#/components/schemas/User"
                example:
                  id: 1
                  name: "张三"
          '404':
            description: "用户不存在"
    

5. 分组与排序

  • Java(SpringFox):通过tags属性分组接口:
    @ApiOperation(value = "用户登录", tags = {"用户认证"})
    @PostMapping("/api/login")
    public ResponseEntity<String> login() {
        // 实现逻辑
    }
    
  • Node.js:通过tags字段分组:
    /api/users/login:
      post:
        tags: ["用户认证"]  # 归类到“用户认证”分组
        summary: "用户登录"
        # ...
    

五、验证与优化

  • 验证文档准确性:使用Swagger Editor(在线工具)检查swagger.yaml是否符合OpenAPI规范;
  • 测试接口:通过Swagger UI的“Try it out”功能直接测试接口,确保文档与实际行为一致;
  • 优化性能:对于大型项目,可通过PathSelectors.ant()过滤路径,减少扫描范围(如仅扫描/api/v1/*)。

0