OpenAPI/Swagger规范分析技能Skill openapi-swagger

这是一个用于OpenAPI和Swagger API规范的专业分析、验证和文档生成工具。它能自动解析API定义文件,检测版本间的破坏性变更,生成高质量的API参考文档(如ReDoc和Swagger UI),并支持多种编程语言的代码示例生成。适用于API开发者、技术文档工程师和DevOps团队,提升API设计质量与开发效率。关键词:OpenAPI, Swagger, API文档, 代码生成, 规范验证, 破坏性变更检测, Spectral, 自动化文档。

后端开发 0 次安装 0 次浏览 更新于 2/26/2026

name: openapi-swagger description: 用于OpenAPI/Swagger规范分析、验证和文档生成的专家技能。解析和验证规范,检测破坏性变更,生成代码示例,并对最佳实践进行代码检查。 allowed-tools: Read, Write, Edit, Bash, Glob, Grep backlog-id: SK-001 metadata: author: babysitter-sdk version: “1.0.0”

OpenAPI/Swagger 技能

用于OpenAPI/Swagger规范分析和文档生成的专家技能。

能力

  • 解析和验证 OpenAPI 3.x 和 Swagger 2.0 规范
  • 从规范生成API文档(ReDoc, Swagger UI)
  • 检测API版本之间的破坏性变更
  • 根据模式验证请求/响应示例
  • 用多种语言生成代码示例
  • 对OpenAPI规范进行最佳实践检查(Spectral规则)
  • 在OpenAPI格式之间转换(YAML/JSON, 版本迁移)

用法

当您需要时调用此技能:

  • 验证和检查OpenAPI规范
  • 生成API参考文档
  • 检测API版本之间的破坏性变更
  • 从API规范创建代码示例
  • 在OpenAPI版本之间迁移

输入

参数 类型 必填 描述
specPath string OpenAPI/Swagger规范文件的路径
action string validate, lint, generate-docs, diff, generate-samples
outputDir string 生成内容的输出目录
targetVersion string 迁移的目标OpenAPI版本
languages array 用于代码示例生成的语言
rulesets array 要应用的Spectral规则集文件

输入示例

{
  "specPath": "./api/openapi.yaml",
  "action": "lint",
  "rulesets": [".spectral.yaml"],
  "outputDir": "docs/api"
}

输出结构

验证输出

{
  "valid": true,
  "errors": [],
  "warnings": [
    {
      "path": "paths./users.get.responses.200",
      "message": "响应应包含描述",
      "severity": "warning"
    }
  ],
  "info": {
    "title": "我的API",
    "version": "1.0.0",
    "openApiVersion": "3.1.0"
  }
}

破坏性变更输出

{
  "breaking": [
    {
      "type": "removed-endpoint",
      "path": "DELETE /users/{id}",
      "description": "新版本中移除了端点"
    },
    {
      "type": "changed-type",
      "path": "POST /users.requestBody.email",
      "from": "string",
      "to": "object"
    }
  ],
  "nonBreaking": [
    {
      "type": "added-endpoint",
      "path": "GET /users/{id}/profile"
    }
  ]
}

OpenAPI 规范模式

OpenAPI 3.1 模板

openapi: 3.1.0
info:
  title: 我的API
  description: API描述,支持**Markdown**
  version: 1.0.0
  contact:
    name: API支持
    email: support@example.com
  license:
    name: MIT
    identifier: MIT

servers:
  - url: https://api.example.com/v1
    description: 生产环境
  - url: https://staging-api.example.com/v1
    description: 预发布环境

tags:
  - name: users
    description: 用户管理操作

paths:
  /users:
    get:
      operationId: listUsers
      summary: 列出所有用户
      description: 返回分页的用户列表
      tags:
        - users
      parameters:
        - $ref: '#/components/parameters/PageParam'
        - $ref: '#/components/parameters/LimitParam'
      responses:
        '200':
          description: 成功响应
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UserList'
              examples:
                success:
                  $ref: '#/components/examples/UserListExample'
        '401':
          $ref: '#/components/responses/Unauthorized'

components:
  schemas:
    User:
      type: object
      required:
        - id
        - email
      properties:
        id:
          type: string
          format: uuid
          description: 唯一标识符
        email:
          type: string
          format: email
          description: 用户邮箱地址
        name:
          type: string
          description: 显示名称
        createdAt:
          type: string
          format: date-time

    UserList:
      type: object
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/User'
        pagination:
          $ref: '#/components/schemas/Pagination'

  parameters:
    PageParam:
      name: page
      in: query
      schema:
        type: integer
        minimum: 1
        default: 1

    LimitParam:
      name: limit
      in: query
      schema:
        type: integer
        minimum: 1
        maximum: 100
        default: 20

  responses:
    Unauthorized:
      description: 需要身份验证
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'

  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

security:
  - bearerAuth: []

Spectral 配置

.spectral.yaml

extends:
  - spectral:oas

rules:
  # 要求描述
  operation-description: warn
  operation-operationId: error

  # 命名约定
  operation-operationId-valid-in-url: true
  path-params: error

  # 安全
  operation-security-defined: error

  # 自定义规则
  path-must-have-tag:
    description: 每个路径必须至少有一个标签
    given: $.paths[*][*]
    severity: warn
    then:
      field: tags
      function: length
      functionOptions:
        min: 1

  require-example:
    description: 响应应包含示例
    given: $.paths[*][*].responses[*].content[*]
    severity: info
    then:
      field: examples
      function: truthy

代码示例生成

生成的示例

// JavaScript (fetch)
const response = await fetch('https://api.example.com/v1/users', {
  method: 'GET',
  headers: {
    'Authorization': 'Bearer YOUR_TOKEN',
    'Content-Type': 'application/json'
  }
});
const data = await response.json();
# Python (requests)
import requests

response = requests.get(
    'https://api.example.com/v1/users',
    headers={
        'Authorization': 'Bearer YOUR_TOKEN',
        'Content-Type': 'application/json'
    }
)
data = response.json()
# cURL
curl -X GET 'https://api.example.com/v1/users' \
  -H 'Authorization: Bearer YOUR_TOKEN' \
  -H 'Content-Type: application/json'

工作流程

  1. 解析规范 - 加载并解析OpenAPI/Swagger文件
  2. 验证语法 - 检查模式合规性
  3. 最佳实践检查 - 应用Spectral规则
  4. 生成文档 - 创建ReDoc/Swagger UI输出
  5. 生成示例 - 创建代码示例
  6. 报告发现 - 输出验证结果

依赖项

{
  "devDependencies": {
    "@stoplight/spectral-cli": "^6.11.0",
    "swagger-cli": "^4.0.0",
    "@redocly/cli": "^1.0.0",
    "openapi-generator-cli": "^2.7.0",
    "oasdiff": "^1.0.0"
  }
}

CLI 命令

# 验证规范
npx @redocly/cli lint openapi.yaml

# Spectral 代码检查
npx spectral lint openapi.yaml

# 生成 ReDoc 文档
npx @redocly/cli build-docs openapi.yaml -o docs/index.html

# 检测破坏性变更
oasdiff breaking old-api.yaml new-api.yaml

# 生成代码示例
npx openapi-generator-cli generate -i openapi.yaml -g typescript-fetch -o ./sdk

应用的最佳实践

  • 使用 $ref 引用可重用组件
  • 为所有模式包含示例
  • 记录所有错误响应
  • 使用语义化版本控制
  • 为所有操作包含 operationId
  • 标记所有端点
  • 为所有环境提供服务器URL

参考

目标流程

  • api-doc-generation.js
  • api-reference-docs.js
  • sdk-doc-generation.js
  • docs-testing.js