温馨提示×

Debian上Swagger的API文档如何编写

小樊
45
2025-12-16 17:13:39
栏目: 智能运维

在 Debian 上编写 Swagger API 文档的实操指南

一 准备环境与工具

  • 安装 Node.js 与 npm(用于 Swagger UI、swagger-jsdoc 等):
    • 执行:sudo apt update && sudo apt install -y nodejs npm
  • 安装 Swagger Editor(本地可视化编辑与校验):
    • 方式一:使用 npm 全局安装 swagger-editor-dist,通过 npx 启动;
    • 方式二:下载官方发布包,解压后用静态服务器(如 http-server)托管 dist 目录并在浏览器访问。
  • 安装 swagger-jsdocswagger-ui-express(Node.js 项目从注释生成或托管 UI):
    • 执行:sudo npm install -g swagger-jsdoc swagger-ui-express
  • 说明:Swagger 现已演进为 OpenAPI Specification(OAS),建议使用 OAS 3.0+ 版本进行编写与维护。

二 编写规范文件

  • 选择规范版本:优先使用 openapi: 3.0.x;若维护老项目,也可使用 swagger: “2.0”
  • 基本结构要点(以 OAS 3.0 为例):
    • openapiinfo(标题、描述、版本)
    • servers(多环境地址)
    • paths(路径与方法,含参数、请求体、响应)
    • components(可复用的 schemas、parameters、responses、securitySchemes)
  • 最小可用示例(openapi 3.0,YAML):
    openapi: 3.0.3
    info:
      title: 示例 API
      description:  Debian 上编写的示例 API 文档
      version: 1.0.0
    servers:
      - url: http://localhost:3000
        description: 本地开发环境
    paths:
      /users:
        get:
          summary: 获取用户列表
          parameters:
            - name: page
              in: query
              required: false
              schema:
                type: integer
                minimum: 1
                default: 1
          responses:
            '200':
              description: 成功返回用户列表
              content:
                application/json:
                  schema:
                    type: array
                    items:
                      $ref: '#/components/schemas/User'
      /users/{id}:
        get:
          summary: 获取单个用户
          parameters:
            - name: id
              in: path
              required: true
              schema:
                type: string
                format: uuid
          responses:
            '200':
              description: 成功返回用户
              content:
                application/json:
                  schema:
                    $ref: '#/components/schemas/User'
            '404':
              description: 用户不存在
    components:
      schemas:
        User:
          type: object
          required:
            - id
            - username
          properties:
            id:
              type: string
              format: uuid
              example: 550e8400-e29b-41d4-a716-446655440000
            username:
              type: string
              minLength: 3
              example: alice
            email:
              type: string
              format: email
              example: alice@example.com
    
  • 若使用 Swagger 2.0,关键字段为 swagger: "2.0"hostbasePathschemespathsdefinitionssecurityDefinitions 等,结构略有差异。

三 本地预览与校验

  • 使用 Swagger Editor 本地预览:
    • 启动编辑器后,将上面的 YAML 粘贴到左侧编辑区,右侧即可交互式预览;也可导入/导出规范文件进行校验。
  • 使用 Node.js + swagger-ui-express 托管文档:
    • 安装:npm i swagger-ui-express
    • 示例代码(保存为 server.js):
      const express = require('express');
      const swaggerUi = require('swagger-ui-express');
      const swaggerDocument = require('./openapi.yaml'); // 或 .json
      
      const app = express();
      app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
      app.listen(3000, () => console.log('Docs at http://localhost:3000/api-docs'));
      
    • 启动服务后访问:http://localhost:3000/api-docs
  • 使用 swagger-jsdoc 从注释生成规范(适合已有 Node.js 代码):
    • 安装:npm i --save-dev swagger-jsdoc
    • 简单配置与命令示例:
      // swagger.js
      const swaggerJsdoc = require('swagger-jsdoc');
      const options = {
        definition: {
          openapi: '3.0.0',
          info: { title: 'API', version: '1.0.0' },
          servers: [{ url: 'http://localhost:3000' }]
        },
        apis: ['./routes/*.js'] // 扫描含注释的路由文件
      };
      const spec = swaggerJsdoc(options);
      console.log(JSON.stringify(spec, null, 2));
      
    • 生成后配合 swagger-ui-express 即可预览。

四 最佳实践与常见要点

  • 采用 OAS 3.0+,保持规范文件自包含、结构清晰、可复用(使用 $ref)。
  • 为每个端点提供完整的 summary/description参数说明请求体示例成功与失败响应(含状态码与示例)。
  • 统一定义 数据模型(schemas),并在多处引用,避免重复;为字段添加 example 提升可用性。
  • 明确 认证与授权(如 API KeyOAuth2Basic Auth),在 components.securitySchemes 定义并在全局或操作级应用。
  • 提供 servers 多环境地址(如生产、预发、开发),便于切换。
  • 使用 tags 对接口分组,增强导航与可读性。
  • 将规范纳入 版本控制,与代码同步更新;通过 Swagger UI/Redoc 提供交互式文档并与规范保持同步。

0