api-documentation

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API Documentation Enforcement

API文档同步强制机制

Overview

概述

Ensures all API changes are reflected in Swagger/OpenAPI documentation. When documentation drift is detected, work pauses until documentation is synchronized.
Core principle: API documentation is a first-class artifact, not an afterthought. No API change ships without documentation.
Announce at start: "I'm using api-documentation to verify Swagger/OpenAPI sync."
确保所有API变更都反映在Swagger/OpenAPI文档中。当检测到文档与代码不一致时,工作会暂停,直到文档同步完成。
核心原则: API文档是一等工件,而非事后补充内容。任何API变更都必须附带对应的文档才能发布。
开始时需告知: "我正在使用api-documentation技能验证Swagger/OpenAPI文档同步情况。"

When This Skill Triggers

技能触发条件

This skill is triggered when ANY of these file patterns are modified:
PatternFrameworkTrigger Reason
**/routes/**/*.ts
Express/FastifyRoute definitions
**/controllers/**/*.ts
NestJS/ExpressController endpoints
**/*.controller.ts
NestJSController class
**/api/**/*.py
FastAPI/FlaskAPI endpoints
**/*_router.py
FastAPIRouter definitions
**/handlers/**/*.go
GoHTTP handlers
**/schema*.ts
TypeScriptSchema definitions
**/dto/**/*.ts
NestJSData transfer objects
**/models/**/*.ts
VariousAPI models
当以下任意文件模式的内容被修改时,将触发本技能:
模式框架触发原因
**/routes/**/*.ts
Express/Fastify路由定义
**/controllers/**/*.ts
NestJS/Express控制器端点
**/*.controller.ts
NestJS控制器类
**/api/**/*.py
FastAPI/FlaskAPI端点
**/*_router.py
FastAPI路由定义
**/handlers/**/*.go
GoHTTP处理器
**/schema*.ts
TypeScript模式定义
**/dto/**/*.ts
NestJS数据传输对象
**/models/**/*.ts
各类框架API模型

Documentation Locations

文档位置

Check these locations for existing API documentation:
FileFormatStandard
openapi.yaml
YAMLOpenAPI 3.x
openapi.json
JSONOpenAPI 3.x
swagger.yaml
YAMLSwagger 2.0
swagger.json
JSONSwagger 2.0
docs/api.yaml
YAMLOpenAPI 3.x
api/openapi.yaml
YAMLOpenAPI 3.x
在以下位置查找现有API文档:
文件格式标准
openapi.yaml
YAMLOpenAPI 3.x
openapi.json
JSONOpenAPI 3.x
swagger.yaml
YAMLSwagger 2.0
swagger.json
JSONSwagger 2.0
docs/api.yaml
YAMLOpenAPI 3.x
api/openapi.yaml
YAMLOpenAPI 3.x

The Protocol

执行流程

Step 1: Detect API Changes

步骤1:检测API变更

bash
undefined
bash
undefined

Check if current changes affect API

Check if current changes affect API

API_CHANGED=false
API_CHANGED=false

Check common API file patterns

Check common API file patterns

for pattern in "routes/" "controllers/" "api/" "handlers/" ".controller.ts" "_router.py"; do if git diff --name-only HEAD~1 | grep -q "$pattern"; then API_CHANGED=true break fi done
for pattern in "routes/" "controllers/" "api/" "handlers/" ".controller.ts" "_router.py"; do if git diff --name-only HEAD~1 | grep -q "$pattern"; then API_CHANGED=true break fi done

Check for schema/DTO changes

Check for schema/DTO changes

if git diff --name-only HEAD~1 | grep -qE "(schema|dto|model)"; then API_CHANGED=true fi
echo "API Changed: $API_CHANGED"
undefined
if git diff --name-only HEAD~1 | grep -qE "(schema|dto|model)"; then API_CHANGED=true fi
echo "API Changed: $API_CHANGED"
undefined

Step 2: Find Documentation File

步骤2:查找文档文件

bash
find_api_docs() {
  for file in openapi.yaml openapi.json swagger.yaml swagger.json \
              docs/api.yaml docs/openapi.yaml api/openapi.yaml; do
    if [ -f "$file" ]; then
      echo "$file"
      return 0
    fi
  done
  return 1
}

DOC_FILE=$(find_api_docs)
if [ -z "$DOC_FILE" ]; then
  echo "ERROR: No API documentation file found"
  echo "PAUSE: Trigger documentation-audit skill"
fi
bash
find_api_docs() {
  for file in openapi.yaml openapi.json swagger.yaml swagger.json \
              docs/api.yaml docs/openapi.yaml api/openapi.yaml; do
    if [ -f "$file" ]; then
      echo "$file"
      return 0
    fi
  done
  return 1
}

DOC_FILE=$(find_api_docs)
if [ -z "$DOC_FILE" ]; then
  echo "ERROR: No API documentation file found"
  echo "PAUSE: Trigger documentation-audit skill"
fi

Step 3: Verify Sync

步骤3:验证同步状态

Compare API code with documentation:
bash
verify_api_sync() {
  local doc_file=$1

  # Extract endpoints from code
  CODE_ENDPOINTS=$(find . -name "*.ts" -path "*/routes/*" -exec grep -h "@(Get|Post|Put|Delete|Patch)" {} \; | \
    sed 's/.*@\(Get\|Post\|Put\|Delete\|Patch\)(\([^)]*\)).*/\1 \2/' | sort -u)

  # Extract endpoints from OpenAPI
  DOC_ENDPOINTS=$(yq '.paths | keys[]' "$doc_file" 2>/dev/null | sort -u)

  # Compare
  MISSING=$(comm -23 <(echo "$CODE_ENDPOINTS" | sort) <(echo "$DOC_ENDPOINTS" | sort))

  if [ -n "$MISSING" ]; then
    echo "DRIFT DETECTED: Endpoints in code but not in docs:"
    echo "$MISSING"
    return 1
  fi

  return 0
}
对比API代码与文档内容:
bash
verify_api_sync() {
  local doc_file=$1

  # Extract endpoints from code
  CODE_ENDPOINTS=$(find . -name "*.ts" -path "*/routes/*" -exec grep -h "@(Get|Post|Put|Delete|Patch)" {} \; | \
    sed 's/.*@\(Get\|Post\|Put\|Delete\|Patch\)(\([^)]*\)).*/\1 \2/' | sort -u)

  # Extract endpoints from OpenAPI
  DOC_ENDPOINTS=$(yq '.paths | keys[]' "$doc_file" 2>/dev/null | sort -u)

  # Compare
  MISSING=$(comm -23 <(echo "$CODE_ENDPOINTS" | sort) <(echo "$DOC_ENDPOINTS" | sort))

  if [ -n "$MISSING" ]; then
    echo "DRIFT DETECTED: Endpoints in code but not in docs:"
    echo "$MISSING"
    return 1
  fi

  return 0
}

Step 4: Handle Drift

步骤4:处理文档不一致情况

If documentation drift is detected:
markdown
undefined
如果检测到文档与代码不一致:
markdown
undefined

API Documentation Drift Detected

API文档不一致已检测

Status: PAUSED Reason: API documentation is out of sync with code
状态: 暂停工作 原因: API文档与代码内容不同步

Missing from Documentation

文档缺失的内容

  • POST /api/users
    (found in
    routes/users.ts:45
    )
  • GET /api/users/:id/profile
    (found in
    routes/users.ts:67
    )
  • POST /api/users
    (位于
    routes/users.ts:45
  • GET /api/users/:id/profile
    (位于
    routes/users.ts:67

Action Required

需执行的操作

  1. Invoke
    documentation-audit
    skill
  2. Update Swagger/OpenAPI documentation
  3. Resume current work after sync complete

api-documentation skill paused work

Then invoke documentation-audit:
Use Skill tool: documentation-audit
undefined
  1. 调用
    documentation-audit
    技能
  2. 更新Swagger/OpenAPI文档
  3. 文档同步完成后恢复工作

api-documentation技能已暂停工作

随后调用documentation-audit技能:
Use Skill tool: documentation-audit
undefined

Documentation Requirements

文档要求

When updating API documentation, include:
更新API文档时,需包含以下内容:

Required Fields

必填字段

FieldDescription
summary
Short description of endpoint
description
Detailed explanation
parameters
All path/query/header params
requestBody
Request schema with examples
responses
All response codes with schemas
tags
Grouping for organization
security
Auth requirements
字段说明
summary
端点的简短描述
description
详细说明
parameters
所有路径/查询/头部参数
requestBody
带示例的请求模式
responses
带模式的所有响应码
tags
用于分类的标签
security
认证要求

Required Examples

必填示例

Every endpoint must have:
  • Request example (for POST/PUT/PATCH)
  • Success response example
  • Error response example
每个端点必须包含:
  • 请求示例(适用于POST/PUT/PATCH方法)
  • 成功响应示例
  • 错误响应示例

Example OpenAPI Entry

OpenAPI示例条目

yaml
/api/users:
  post:
    summary: Create a new user
    description: |
      Creates a new user account with the provided details.
      Requires admin authentication.
    tags:
      - Users
    security:
      - bearerAuth: []
    requestBody:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/CreateUserRequest'
          example:
            email: user@example.com
            name: John Doe
            role: member
    responses:
      '201':
        description: User created successfully
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/User'
            example:
              id: usr_123abc
              email: user@example.com
              name: John Doe
              role: member
              createdAt: '2025-01-02T10:30:00Z'
      '400':
        description: Invalid request body
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Error'
            example:
              code: VALIDATION_ERROR
              message: Email is required
      '401':
        description: Authentication required
      '403':
        description: Insufficient permissions
yaml
/api/users:
  post:
    summary: Create a new user
    description: |
      Creates a new user account with the provided details.
      Requires admin authentication.
    tags:
      - Users
    security:
      - bearerAuth: []
    requestBody:
      required: true
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/CreateUserRequest'
          example:
            email: user@example.com
            name: John Doe
            role: member
    responses:
      '201':
        description: User created successfully
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/User'
            example:
              id: usr_123abc
              email: user@example.com
              name: John Doe
              role: member
              createdAt: '2025-01-02T10:30:00Z'
      '400':
        description: Invalid request body
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Error'
            example:
              code: VALIDATION_ERROR
              message: Email is required
      '401':
        description: Authentication required
      '403':
        description: Insufficient permissions

Validation

验证操作

After updating documentation, validate:
bash
undefined
更新文档后,执行以下验证:
bash
undefined

Validate OpenAPI spec

Validate OpenAPI spec

npx @apidevtools/swagger-cli validate openapi.yaml
npx @apidevtools/swagger-cli validate openapi.yaml

Or with yq for basic structure check

Or with yq for basic structure check

yq 'has("openapi") and has("paths") and has("info")' openapi.yaml
undefined
yq 'has("openapi") and has("paths") and has("info")' openapi.yaml
undefined

Checklist

检查清单

Before resuming work:
  • API documentation file exists
  • All endpoints are documented
  • Request/response schemas defined
  • Examples provided for all operations
  • Security requirements documented
  • Documentation validates successfully
  • Changes committed to branch
恢复工作前需确认:
  • 存在API文档文件
  • 所有端点已完成文档编写
  • 已定义请求/响应模式
  • 所有操作都提供了示例
  • 已记录安全要求
  • 文档验证通过
  • 变更已提交至分支

Integration

集成说明

This skill coordinates with:
SkillPurpose
documentation-audit
Full documentation sync
issue-driven-development
Triggered during implementation
comprehensive-review
Validates documentation complete
本技能与以下技能协同工作:
技能用途
documentation-audit
完成文档全量同步
issue-driven-development
在实现阶段触发
comprehensive-review
验证文档完整性

When to Skip

可跳过场景

This skill can be skipped when:
  • Changes are purely internal (no API surface change)
  • Changes are to test files only
  • Changes are to documentation itself
  • Project has no API (CLI tool, library, etc.)
在以下场景中可跳过本技能:
  • 变更仅涉及内部逻辑(未修改API对外暴露的内容)
  • 变更仅针对测试文件
  • 变更仅针对文档本身
  • 项目无API(如CLI工具、类库等)