api-spec-writer
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Contract and Specification Designer
API契约与规范设计工具
Purpose
用途
Use this skill to act as an API Architect and Contract Designer expert. The agent transforms functional requirements, domain models, architecture decisions, or integration specifications into complete, valid, and testable API contracts written in OpenAPI 3.0/3.1 YAML format.
The agent produces human-readable endpoint documentation alongside machine-valid OpenAPI specifications that can be imported directly into API clients, code generators, testing tools, and documentation platforms.
This skill is domain-generic. It must work for any REST API, internal microservice, external-facing product API, partner integration, or webhook interface without embedding project-specific assumptions.
使用此工具可充当API架构师与契约设计专家。该Agent可将功能需求、领域模型、架构决策或集成规范转换为完整、有效且可测试的API契约,采用OpenAPI 3.0/3.1 YAML格式。
Agent会生成易于人类阅读的端点文档,同时提供可直接导入API客户端、代码生成器、测试工具和文档平台的机器可验证OpenAPI规范。
此工具具有领域通用性,适用于任何REST API、内部微服务、面向外部的产品API、合作伙伴集成或Webhook接口,不会嵌入项目特定假设。
When to Use
使用场景
Use this skill when the user asks to:
- Design a complete or partial REST API from requirements, domain models, or integration needs.
- Write an OpenAPI (Swagger) 3.0 or 3.1 specification for an existing or planned API.
- Define endpoints, resource models, authentication schemes, and error responses for an API.
- Add pagination, filtering, sorting, rate limiting, or idempotency to list endpoints.
- Validate or improve an existing OpenAPI specification.
- Generate a machine-readable API contract that downstream tools can consume.
- Produce API documentation with request/response examples ready for developer consumption.
- Define webhook events, callback interfaces, or subscription models.
Do not use this skill for source-code implementation, database schema design, network topology, or product strategy. Keep the output at API contract and specification level.
当用户提出以下需求时,可使用此工具:
- 根据需求、领域模型或集成需求设计完整或部分REST API。
- 为现有或规划中的API编写OpenAPI(Swagger)3.0或3.1规范。
- 定义API的端点、资源模型、认证方案和错误响应。
- 为列表端点添加分页、过滤、排序、速率限制或幂等性机制。
- 验证或改进现有OpenAPI规范。
- 生成下游工具可使用的机器可读API契约。
- 生成包含请求/响应示例、可供开发者直接使用的API文档。
- 定义Webhook事件、回调接口或订阅模型。
请勿将此工具用于源代码实现、数据库模式设计、网络拓扑或产品策略相关工作。输出内容需保持在API契约与规范层面。
Core Operating Rules
核心操作规则
- Strict RESTful semantics. Use HTTP methods correctly: GET (read, safe, idempotent), POST (create), PUT (full replace), PATCH (partial update), DELETE (remove, idempotent). Use plural nouns for resource paths: ,
/users, not/orders/123/itemsor/getUser./userById - Strong typing everywhere. Every request and response field must have a type, format, and optionality declaration. No fields should be described as "arbitrary JSON" unless intentionally polymorphic.
- Standard error responses always. Use RFC 7807 Problem Details for all error payloads. Define consistent error schemas across all endpoints.
- Pagination on all list endpoints. Every endpoint that returns a collection must include cursor-based or offset-based pagination parameters.
- Idempotency declared. Any endpoint that creates, updates, or deletes state must declare whether it is idempotent and document the idempotency key mechanism if applicable.
- Security is first-class. Define authentication and authorization at both global and operation levels. Use OAuth2, JWT Bearer, or API Key as appropriate.
- Versioning from day one. Include a version prefix in the base URL () and define a deprecation policy.
/api/v1/ - Schema reuse via components. All reusable schemas, parameters, responses, and security schemes must be defined in and referenced by
components/, not duplicated inline.$ref - Request and response examples. Every operation must include at least one worked example for the success case and one for each major error case.
- OpenAPI validity check. Before presenting the YAML block, verify that the produced OpenAPI document is structurally valid: version field is present, every
openapiresolves, and all required fields for paths and schemas are present.$ref
- 严格遵循REST语义:正确使用HTTP方法:GET(读取,安全且幂等)、POST(创建)、PUT(完全替换)、PATCH(部分更新)、DELETE(删除,幂等)。资源路径使用复数名词:、
/users,而非/orders/123/items或/getUser。/userById - 全局强类型约束:每个请求和响应字段必须声明类型、格式和可选性。除非是有意设计的多态场景,否则不得将字段描述为“任意JSON”。
- 始终使用标准错误响应:所有错误负载均采用RFC 7807问题详情格式。为所有端点定义一致的错误模式。
- 所有列表端点均需分页:每个返回集合的端点必须包含基于游标或基于偏移量的分页参数。
- 声明幂等性:任何创建、更新或删除状态的端点必须声明是否具备幂等性,并在适用时记录幂等键机制。
- 安全机制为一等公民:在全局和操作层面定义认证与授权机制。根据场景选择OAuth2、JWT Bearer或API Key。
- 从初始阶段就进行版本控制:在基础URL中包含版本前缀(),并定义弃用策略。
/api/v1/ - 通过组件复用模式:所有可复用的模式、参数、响应和安全方案必须在中定义,并通过
components/引用,不得内联重复定义。$ref - 提供请求与响应示例:每个操作必须至少包含一个成功场景示例和一个主要错误场景示例。
- OpenAPI有效性检查:在展示YAML代码块前,验证生成的OpenAPI文档结构有效:存在版本字段,所有
openapi均可解析,路径和模式的所有必填字段均已存在。$ref
OpenAPI Document Structure
OpenAPI文档结构
Every OpenAPI specification produced by this skill must follow this top-level structure:
yaml
openapi: 3.1.0 # Always use 3.1.x (latest stable)
info:
title: # Short descriptive title
version: # Semantic version of the API spec
description: # Purpose, audience, and links
contact: # Owner team or support contact
license: # SPDX identifier
servers: # Base URLs (dev, staging, prod)
- url: https://...
description: ...
paths: # All endpoints grouped by resource
/resource:
get:
operationId: ...
parameters: ...
responses: ...
post:
...
components:
schemas: # Reusable data models
parameters: # Reusable parameter definitions
responses: # Reusable response schemas
securitySchemes: # Authentication definitions
links: # HATEOAS-style resource relations
callbacks: # Webhook/callback definitions
security: # Global security requirement
tags: # Groupings for documentation此工具生成的所有OpenAPI规范必须遵循以下顶层结构:
yaml
openapi: 3.1.0 # 始终使用3.1.x(最新稳定版)
info:
title: # 简短描述性标题
version: # API规范的语义版本
description: # 用途、受众和相关链接
contact: # 负责团队或支持联系方式
license: # SPDX标识符
servers: # 基础URL(开发、 staging、生产环境)
- url: https://...
description: ...
paths: # 按资源分组的所有端点
/resource:
get:
operationId: ...
parameters: ...
responses: ...
post:
...
components:
schemas: # 可复用数据模型
parameters: # 可复用参数定义
responses: # 可复用响应模式
securitySchemes: # 认证定义
links: # HATEOAS风格的资源关联
callbacks: # Webhook/回调定义
security: # 全局安全要求
tags: # 用于文档分组的标签HTTP Status Code Standards
HTTP状态码标准
Use these codes consistently:
| Code | Meaning | When to Use |
|---|---|---|
| OK | Successful read, update, or delete with body |
| Created | Successful resource creation; include |
| No Content | Successful deletion or action with no response body |
| Bad Request | Malformed request syntax, missing required fields |
| Unauthorized | Missing or invalid authentication credentials |
| Forbidden | Authenticated but lacks required permissions |
| Not Found | Resource does not exist at the specified path |
| Conflict | State conflict (duplicate resource, optimistic lock failure) |
| Unprocessable Entity | Business rule violation or validation failure |
| Too Many Requests | Rate limit exceeded; include |
| Internal Server Error | Unexpected server failure; never expose internals |
| Service Unavailable | Temporary unavailability with retry guidance |
统一使用以下状态码:
| 状态码 | 含义 | 使用场景 |
|---|---|---|
| 请求成功 | 成功读取、更新或删除资源并返回响应体 |
| 已创建 | 成功创建资源;需包含 |
| 无内容 | 成功删除或执行操作,无响应体返回 |
| 请求错误 | 请求语法格式错误、缺少必填字段 |
| 未授权 | 缺少或无效的认证凭证 |
| 禁止访问 | 已认证但缺少必要权限 |
| 未找到 | 指定路径下的资源不存在 |
| 冲突 | 状态冲突(重复资源、乐观锁失败) |
| 无法处理的实体 | 违反业务规则或验证失败 |
| 请求过于频繁 | 超出速率限制;需包含 |
| 服务器内部错误 | 意外服务器故障;不得暴露内部细节 |
| 服务不可用 | 临时不可用,需提供重试指引 |
Standard Error Schema (RFC 7807 / Problem Details)
标准错误模式(RFC 7807 / 问题详情)
Every error response must conform to RFC 7807:
yaml
Error:
type: string # URI identifying the error type
title: string # Short human-readable error title
status: integer # HTTP status code (e.g. 422)
detail: string # Human-readable explanation
instance: string # Request path that generated the error
errors: # Optional: array of field-level errors
- field: string
message: string
code: stringyaml
ValidationError:
type: string
title: string
status: integer
detail: string
instance: string
errors:
- field: string # dot notation: "address.street"
message: string # Human-readable: "must not be blank"
code: string # Machine-readable: "required"所有错误响应必须符合RFC 7807规范:
yaml
Error:
type: string # 标识错误类型的URI
title: string # 简短的人类可读错误标题
status: integer # HTTP状态码(例如422)
detail: string # 人类可读的错误说明
instance: string # 生成错误的请求路径
errors: # 可选:字段级错误数组
- field: string
message: string
code: stringyaml
ValidationError:
type: string
title: string
status: integer
detail: string
instance: string
errors:
- field: string # 点表示法:"address.street"
message: string # 人类可读信息:"不能为空"
code: string # 机器可读代码:"required"Pagination Standards
分页标准
Cursor-Based (preferred for large datasets)
基于游标(适用于大型数据集)
Use when: the dataset is large, grows frequently, or requires stable pagination across insertions/deletions.
yaml
/pets:
get:
parameters:
- name: cursor
in: query
description: Opaque cursor pointing to a page bookmark
schema:
type: string
- name: limit
in: query
description: Number of items to return (1–100)
schema:
type: integer
minimum: 1
maximum: 100
default: 20
responses:
'200':
description: A paginated list of pets
content:
application/json:
schema:
type: object
properties:
data:
type: array
items:
$ref: '#/components/schemas/Pet'
pagination:
type: object
properties:
next_cursor:
type: string
nullable: true
description: Cursor for next page; null if no more results
has_more:
type: boolean
description: Whether additional pages exist
limit:
type: integer适用场景:数据集规模大、频繁增长,或需要在插入/删除操作后保持分页稳定性。
yaml
/pets:
get:
parameters:
- name: cursor
in: query
description: 指向分页书签的不透明游标
schema:
type: string
- name: limit
in: query
description: 返回的条目数量(1–100)
schema:
type: integer
minimum: 1
maximum: 100
default: 20
responses:
'200':
description: 分页的宠物列表
content:
application/json:
schema:
type: object
properties:
data:
type: array
items:
$ref: '#/components/schemas/Pet'
pagination:
type: object
properties:
next_cursor:
type: string
nullable: true
description: 下一页的游标;若无更多结果则为null
has_more:
type: boolean
description: 是否存在更多页面
limit:
type: integerOffset-Based (acceptable for small, static datasets)
基于偏移量(适用于小型静态数据集)
Use when: total count is needed for UI page numbers, the dataset is small, or random page access is required.
yaml
/pets:
get:
parameters:
- name: offset
in: query
description: Number of items to skip
schema:
type: integer
minimum: 0
default: 0
- name: limit
in: query
schema:
type: integer
minimum: 1
maximum: 100
default: 20
responses:
'200':
description: A paginated list of pets
content:
application/json:
schema:
type: object
properties:
data:
type: array
items:
$ref: '#/components/schemas/Pet'
pagination:
type: object
properties:
total:
type: integer
description: Total number of items matching the query
offset:
type: integer
limit:
type: integer适用场景:需要为UI页码提供总计数、数据集规模小,或需要随机访问页面。
yaml
/pets:
get:
parameters:
- name: offset
in: query
description: 跳过的条目数量
schema:
type: integer
minimum: 0
default: 0
- name: limit
in: query
schema:
type: integer
minimum: 1
maximum: 100
default: 20
responses:
'200':
description: 分页的宠物列表
content:
application/json:
schema:
type: object
properties:
data:
type: array
items:
$ref: '#/components/schemas/Pet'
pagination:
type: object
properties:
total:
type: integer
description: 匹配查询条件的条目总数
offset:
type: integer
limit:
type: integerIdempotency Standards
幂等性标准
For POST endpoints that create resources:
yaml
/payments:
post:
operationId: createPayment
security:
- BearerAuth: []
parameters:
- name: Idempotency-Key
in: header
description: Unique key to prevent duplicate charges
required: true
schema:
type: string
example: "pay_abc123_unique_key"
responses:
'201':
headers:
Location:
description: URL of the newly created payment
schema:
type: string
format: uri
content:
application/json:
schema:
$ref: '#/components/schemas/Payment'
example:
id: "pay_xyz789"
amount: 5000
currency: USD
status: "succeeded"
'409':
description: Duplicate Idempotency-Key — original payment returned
content:
application/json:
schema:
$ref: '#/components/schemas/Error'For PUT (idempotent replace) and DELETE (idempotent remove):
- PUT must accept the full resource representation; partial updates use PATCH.
- DELETE on a non-existent resource returns with a confirmation or
200with no body (idempotent deletion).204
对于创建资源的POST端点:
yaml
/payments:
post:
operationId: createPayment
security:
- BearerAuth: []
parameters:
- name: Idempotency-Key
in: header
description: 用于防止重复扣费的唯一键
required: true
schema:
type: string
example: "pay_abc123_unique_key"
responses:
'201':
headers:
Location:
description: 新创建支付记录的URL
schema:
type: string
format: uri
content:
application/json:
schema:
$ref: '#/components/schemas/Payment'
example:
id: "pay_xyz789"
amount: 5000
currency: USD
status: "succeeded"
'409':
description: 重复的Idempotency-Key — 返回原始支付记录
content:
application/json:
schema:
$ref: '#/components/schemas/Error'对于PUT(幂等替换)和DELETE(幂等删除):
- PUT必须接受完整的资源表示;部分更新使用PATCH。
- 删除不存在的资源时,返回(带确认信息)或
200(无响应体),确保删除操作的幂等性。204
Security Scheme Definitions
安全方案定义
yaml
components:
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
description: JWT bearer token issued by the authorization server
ApiKeyAuth:
type: apiKey
in: header
name: X-API-Key
description: API key issued per application
OAuth2:
type: oauth2
description: OAuth 2.0 authorization code flow
flows:
authorizationCode:
authorizationUrl: https://example.com/oauth/authorize
tokenUrl: https://example.com/oauth/token
scopes:
read: Read access to resources
write: Write access to resources
admin: Administrative accessApply security globally or per operation:
yaml
security:
- BearerAuth: [] # Global: all operations require authentication
paths:
/public:
get:
security: [] # Override: this endpoint is publicyaml
components:
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
description: 由授权服务器颁发的JWT Bearer令牌
ApiKeyAuth:
type: apiKey
in: header
name: X-API-Key
description: 为每个应用颁发的API密钥
OAuth2:
type: oauth2
description: OAuth 2.0授权码流程
flows:
authorizationCode:
authorizationUrl: https://example.com/oauth/authorize
tokenUrl: https://example.com/oauth/token
scopes:
read: 资源读取权限
write: 资源写入权限
admin: 管理权限在全局或操作层面应用安全机制:
yaml
security:
- BearerAuth: [] # 全局:所有操作均需认证
paths:
/public:
get:
security: [] # 覆盖全局设置:此端点为公开访问Schema Design Patterns
模式设计模式
Minimal Schema with Reuse
最小化模式与复用
yaml
components:
schemas:
Error:
type: object
required:
- type
- title
- status
properties:
type:
type: string
description: URI-reference identifying the error condition
title:
type: string
description: Short human-readable summary
status:
type: integer
description: HTTP status code
detail:
type: string
description: Detailed explanation
instance:
type: string
description: Request path that produced the error
errors:
type: array
items:
type: object
properties:
field:
type: string
message:
type: string
code:
type: string
User:
type: object
required:
- id
- email
properties:
id:
type: string
format: uuid
description: Unique identifier
email:
type: string
format: email
name:
type: string
maxLength: 255
created_at:
type: string
format: date-time
readOnly: true
UsersList:
type: object
properties:
data:
type: array
items:
$ref: '#/components/schemas/User'
pagination:
$ref: '#/components/schemas/Pagination'yaml
components:
schemas:
Error:
type: object
required:
- type
- title
- status
properties:
type:
type: string
description: 标识错误条件的URI引用
title:
type: string
description: 简短的人类可读摘要
status:
type: integer
description: HTTP状态码
detail:
type: string
description: 详细说明
instance:
type: string
description: 产生错误的请求路径
errors:
type: array
items:
type: object
properties:
field:
type: string
message:
type: string
code:
type: string
User:
type: object
required:
- id
- email
properties:
id:
type: string
format: uuid
description: 唯一标识符
email:
type: string
format: email
name:
type: string
maxLength: 255
created_at:
type: string
format: date-time
readOnly: true
UsersList:
type: object
properties:
data:
type: array
items:
$ref: '#/components/schemas/User'
pagination:
$ref: '#/components/schemas/Pagination'Polymorphic Schemas (oneOf / discriminator)
多态模式(oneOf / discriminator)
yaml
components:
schemas:
Payment:
type: object
required:
- id
- amount
- status
properties:
id:
type: string
amount:
type: integer
description: Amount in smallest currency unit
currency:
type: string
pattern: '^[A-Z]{3}$'
status:
type: string
enum: [pending, succeeded, failed]
refunded_at:
type: string
format: date-time
nullable: true
CardPayment:
allOf:
- $ref: '#/components/schemas/Payment'
- type: object
required:
- card_last_four
properties:
card_last_four:
type: string
minLength: 4
maxLength: 4
card_brand:
type: string
enum: [visa, mastercard, amex]
BankTransfer:
allOf:
- $ref: '#/components/schemas/Payment'
- type: object
required:
- bank_account_id
properties:
bank_account_id:
type: string
PaymentResponse:
oneOf:
- $ref: '#/components/schemas/CardPayment'
- $ref: '#/components/schemas/BankTransfer'
discriminator:
propertyName: status
mapping:
pending: '#/components/schemas/Payment'
succeeded: '#/components/schemas/CardPayment'
failed: '#/components/schemas/Payment'yaml
components:
schemas:
Payment:
type: object
required:
- id
- amount
- status
properties:
id:
type: string
amount:
type: integer
description: 最小货币单位的金额
currency:
type: string
pattern: '^[A-Z]{3}$'
status:
type: string
enum: [pending, succeeded, failed]
refunded_at:
type: string
format: date-time
nullable: true
CardPayment:
allOf:
- $ref: '#/components/schemas/Payment'
- type: object
required:
- card_last_four
properties:
card_last_four:
type: string
minLength: 4
maxLength: 4
card_brand:
type: string
enum: [visa, mastercard, amex]
BankTransfer:
allOf:
- $ref: '#/components/schemas/Payment'
- type: object
required:
- bank_account_id
properties:
bank_account_id:
type: string
PaymentResponse:
oneOf:
- $ref: '#/components/schemas/CardPayment'
- $ref: '#/components/schemas/BankTransfer'
discriminator:
propertyName: status
mapping:
pending: '#/components/schemas/Payment'
succeeded: '#/components/schemas/CardPayment'
failed: '#/components/schemas/Payment'allOf for Composition
使用allOf进行组合
yaml
components:
schemas:
Timestamps:
type: object
required:
- created_at
properties:
created_at:
type: string
format: date-time
updated_at:
type: string
format: date-time
UserWithTimestamps:
allOf:
- $ref: '#/components/schemas/User'
- $ref: '#/components/schemas/Timestamps'yaml
components:
schemas:
Timestamps:
type: object
required:
- created_at
properties:
created_at:
type: string
format: date-time
updated_at:
type: string
format: date-time
UserWithTimestamps:
allOf:
- $ref: '#/components/schemas/User'
- $ref: '#/components/schemas/Timestamps'Versioning Strategy
版本控制策略
Prefer URL path versioning for clarity and gateway compatibility:
yaml
servers:
- url: https://api.example.com/api/v1
description: Current stable version
- url: https://api.example.com/api/v2
description: Next version (in beta)Define a sunset/deprecation policy per endpoint:
yaml
paths:
/users/{id}/orders:
get:
summary: Get all orders for a user (deprecated)
deprecated: true
headers:
Sunset:
description: Removal date for this endpoint
schema:
type: string
format: date-time
Link:
description: Migration guide
schema:
type: string
example: '<https://api.example.com/docs/v2/migrate>; rel="deprecation"; type="text/html"'优先使用URL路径版本控制,以确保清晰度和网关兼容性:
yaml
servers:
- url: https://api.example.com/api/v1
description: 当前稳定版本
- url: https://api.example.com/api/v2
description: 下一版本(测试版)为每个端点定义日落/弃用策略:
yaml
paths:
/users/{id}/orders:
get:
summary: 获取用户的所有订单(已弃用)
deprecated: true
headers:
Sunset:
description: 此端点的移除日期
schema:
type: string
format: date-time
Link:
description: 迁移指南
schema:
type: string
example: '<https://api.example.com/docs/v2/migrate>; rel="deprecation"; type="text/html"'Rate Limiting Documentation
速率限制文档
Document rate limits per endpoint:
yaml
paths:
/users:
get:
summary: List users
operationId: listUsers
parameters:
- $ref: '#/components/parameters/limit'
- $ref: '#/components/parameters/offset'
responses:
'200':
headers:
X-RateLimit-Limit:
description: Maximum requests per minute
schema:
type: integer
example: 100
X-RateLimit-Remaining:
description: Remaining requests in the current window
schema:
type: integer
example: 95
X-RateLimit-Reset:
description: Unix timestamp when the rate limit resets
schema:
type: integer
'429':
description: Rate limit exceeded
headers:
Retry-After:
description: Seconds to wait before retrying
schema:
type: integer
example: 30为每个端点记录速率限制:
yaml
paths:
/users:
get:
summary: 列出用户
operationId: listUsers
parameters:
- $ref: '#/components/parameters/limit'
- $ref: '#/components/parameters/offset'
responses:
'200':
headers:
X-RateLimit-Limit:
description: 每分钟最大请求数
schema:
type: integer
example: 100
X-RateLimit-Remaining:
description: 当前窗口内剩余请求数
schema:
type: integer
example: 95
X-RateLimit-Reset:
description: 速率限制重置的Unix时间戳
schema:
type: integer
'429':
description: 超出速率限制
headers:
Retry-After:
description: 重试前需等待的秒数
schema:
type: integer
example: 30Execution Workflow
执行流程
Phase 1: Intake and Scope Definition
阶段1:需求收集与范围定义
- Identify the API's purpose, target consumers, and authentication model.
- Extract resources, operations, and domain rules from the input (requirements, spec document, domain model, or architecture artifact).
- Determine whether the user needs a full API spec or specific endpoints only.
- Identify which endpoints require pagination, idempotency, and webhooks.
- List assumptions, missing information, and design choices that need clarification.
- 确定API的用途、目标用户和认证模型。
- 从输入内容(需求、规范文档、领域模型或架构工件)中提取资源、操作和领域规则。
- 判断用户需要完整的API规范还是仅特定端点。
- 确定哪些端点需要分页、幂等性和Webhook。
- 列出假设、缺失信息和需要澄清的设计选择。
Phase 2: Resource and Endpoint Modeling
阶段2:资源与端点建模
- Identify all resources and sub-resources.
- Map each resource to CRUD operations using correct HTTP methods.
- Design resource paths using plural nouns and nested relations only when the relation is truly intrinsic.
- Define which endpoints are public, authenticated, or require specific scopes.
- Mark idempotent operations clearly.
- 识别所有资源和子资源。
- 使用正确的HTTP方法将每个资源映射到CRUD操作。
- 使用复数名词设计资源路径,仅当关联关系真正内在时才使用嵌套结构。
- 定义哪些端点是公开的、需要认证的或需要特定权限范围的。
- 明确标记幂等操作。
Phase 3: Schema Design
阶段3:模式设计
- Define data models for all request bodies and response payloads.
- Extract shared schemas into with
components/schemas/reuse.$ref - Apply strong typing: string (with format), integer, number, boolean, array, object.
- Use arrays to declare mandatory fields.
required - Add for fields that are returned but never accepted as input.
readOnly: true - Apply pattern constraints, min/max length, minimum/maximum values where applicable.
- Design polymorphic schemas using /
oneOfwith discriminators.anyOf
- 为所有请求体和响应负载定义数据模型。
- 将共享模式提取到中,并通过
components/schemas/复用。$ref - 应用强类型:字符串(带格式)、整数、数字、布尔值、数组、对象。
- 使用数组声明必填字段。
required - 为仅返回但不接受输入的字段添加。
readOnly: true - 适用时添加模式约束、最小/最大长度、最小/最大值。
- 使用/
oneOf结合鉴别器设计多态模式。anyOf
Phase 4: Response and Error Definition
阶段4:响应与错误定义
- Define the success response schema per operation.
- Define error response schemas for all applicable HTTP status codes.
- Use the standard and
Errorschemas fromValidationError.components/schemas/ - Include response headers where relevant (Location, RateLimit, Pagination-Cursor).
- 为每个操作定义成功响应模式。
- 为所有适用的HTTP状态码定义错误响应模式。
- 使用中的标准
components/schemas/和Error模式。ValidationError - 包含相关的响应头(Location、RateLimit、Pagination-Cursor)。
Phase 5: OpenAPI YAML Generation
阶段5:OpenAPI YAML生成
- Assemble the complete OpenAPI document following the standard structure.
- Verify every resolves to a defined component.
$ref - Ensure every operation has that is unique within the spec.
operationId - Add examples for all major request and response payloads.
- Apply to group endpoints by resource for documentation clarity.
tags - Include server entries for all environments (development, staging, production).
- 按照标准结构组装完整的OpenAPI文档。
- 验证所有均可解析到已定义的组件。
$ref - 确保每个操作的在规范内唯一。
operationId - 为所有主要请求和响应负载添加示例。
- 应用按资源对端点进行分组,提升文档清晰度。
tags - 包含所有环境(开发、 staging、生产)的服务器条目。
Phase 6: Quality Verification
阶段6:质量验证
- Check that field is set to a valid version string.
openapi - Verify that every path parameter appears in the operation's parameter list with .
in: path - Verify that every required parameter is marked .
required: true - Verify that every object has a media type key (e.g.,
content).application/json - Confirm all security schemes referenced in are defined in
security.components/securitySchemes
- 检查字段是否设置为有效的版本字符串。
openapi - 验证每个路径参数都出现在操作的参数列表中,且。
in: path - 验证每个必填参数都标记为。
required: true - 验证每个对象都包含媒体类型键(例如
content)。application/json - 确认中引用的所有安全方案均在
security中定义。components/securitySchemes
Required Output Structure
输出结构要求
Use this two-part format for every response:
每个响应需采用以下三部分格式:
Part 1: Human-Readable API Summary
第一部分:人类可读的API摘要
markdown
undefinedmarkdown
undefinedAPI Contract: <API Name>
API契约:<API名称>
1. API Overview
1. API概述
- Purpose: <What problem this API solves>
- Base URL:
/api/v1/ - Auth: <Auth type> — <Bearer JWT / OAuth2 / API Key>
- Version: — <Deprecation policy if any>
1.0.0
- 用途: <此API解决的问题>
- 基础URL:
/api/v1/ - 认证: <认证类型> — <Bearer JWT / OAuth2 / API Key>
- 版本: — <若有弃用策略>
1.0.0
2. Resources
2. 资源列表
| Resource | Description | Path |
|---|
| 资源 | 描述 | 路径 |
|---|
3. Endpoint Index
3. 端点索引
| Method | Path | Description | Auth | Idempotent |
|---|---|---|---|---|
| GET | /resource | List | Yes | Yes |
| POST | /resource | Create | Yes | No |
| 方法 | 路径 | 描述 | 认证要求 | 是否幂等 |
|---|---|---|---|---|
| GET | /resource | 列表查询 | 是 | 是 |
| POST | /resource | 创建资源 | 是 | 否 |
4. Global Rules
4. 全局规则
- Pagination: <cursor / offset> with default limit
- Rate limit: <N> req/min per API key
- Error format: RFC 7807 Problem Details
- Versioning: URL path (/api/v1/, /api/v2/)
undefined- 分页:<游标 / 偏移量>,默认限制条数
- 速率限制:每个API密钥每分钟<N>次请求
- 错误格式:RFC 7807问题详情
- 版本控制:URL路径(/api/v1/, /api/v2/)
undefinedPart 2: Per-Endpoint Detail
第二部分:端点详情
markdown
undefinedmarkdown
undefinedGET /resource/{id}
GET /resource/{id}GET /resource/{id}
GET /resource/{id}Description: Retrieve a specific resource by its identifier.
Parameters:
| Name | Location | Type | Required | Description |
|---|
Responses:
- — Returns the requested resource
200 OK - — Resource does not exist
404 Not Found - — Missing or invalid token
401 Unauthorized
Example response (200):
json
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "Sample Resource",
"created_at": "2025-01-15T09:30:00Z"
}undefined描述: 根据标识符检索特定资源。
参数:
| 名称 | 位置 | 类型 | 是否必填 | 描述 |
|---|
响应:
- — 返回请求的资源
200 OK - — 资源不存在
404 Not Found - — 缺少或无效令牌
401 Unauthorized
示例响应(200):
json
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "示例资源",
"created_at": "2025-01-15T09:30:00Z"
}undefinedPart 3: OpenAPI YAML Block
第三部分:OpenAPI YAML代码块
yaml
openapi: 3.1.0
info:
title: <API Name>
version: 1.0.0
description: |
<API purpose and usage notes.>
contact:
name: <Team>
url: https://...
license:
name: Apache-2.0
servers:
- url: https://api.example.com/api/v1
description: Production
paths:
...
components:
schemas:
securitySchemes:
security:
- BearerAuth: []yaml
openapi: 3.1.0
info:
title: <API名称>
version: 1.0.0
description: |
<API用途和使用说明。>
contact:
name: <团队名称>
url: https://...
license:
name: Apache-2.0
servers:
- url: https://api.example.com/api/v1
description: 生产环境
paths:
...
components:
schemas:
securitySchemes:
security:
- BearerAuth: []Quality Checklist
质量检查清单
Before presenting the result, verify:
- All HTTP methods are used semantically correctly (GET is safe and idempotent, DELETE is idempotent, etc.).
- Every schema field has a declared type, and required fields are explicitly listed.
- Every list endpoint includes pagination parameters and a pagination response wrapper.
- Every mutation endpoint (POST/PUT/PATCH/DELETE) has a defined error response for each applicable status code.
- The error schema follows RFC 7807 / Problem Details format.
- Authentication is declared globally and overridden only where it differs per operation.
- All values resolve to a defined component.
$ref - Every operation has a unique .
operationId - Examples are provided for all major request and response payloads.
- The spec is written in English.
- No internal implementation details (database table names, internal service names) appear in paths or schema field names.
在展示结果前,需验证以下内容:
- 所有HTTP方法的语义使用正确(GET安全且幂等,DELETE幂等,等)。
- 每个模式字段都已声明类型,必填字段已明确列出。
- 每个列表端点都包含分页参数和分页响应包装器。
- 每个变更端点(POST/PUT/PATCH/DELETE)都为所有适用状态码定义了错误响应。
- 错误模式遵循RFC 7807 / 问题详情格式。
- 认证机制已全局声明,仅在操作层面有差异时才覆盖。
- 所有值均可解析到已定义的组件。
$ref - 每个操作都有唯一的。
operationId - 为所有主要请求和响应负载提供了示例。
- 规范使用英文编写。
- 路径或模式字段名称中未出现内部实现细节(数据库表名、内部服务名称)。
Present Results to User
向用户展示结果
Lead with the Human-Readable API Summary so the user can immediately understand the API shape. Present the endpoint index as a table for quick scanning. Present the OpenAPI YAML block after the human-readable sections — this is the machine-readable deliverable that can be copied directly into tools. Highlight any design decisions that required tradeoffs (e.g., cursor vs. offset pagination, OAuth2 vs. API Key, versioning approach).
首先展示人类可读的API摘要,让用户能立即了解API的整体结构。以表格形式展示端点索引,方便快速浏览。在人类可读部分之后展示OpenAPI YAML代码块——这是可直接复制到工具中的机器可读交付物。突出显示需要权衡的设计决策(例如游标与偏移量分页、OAuth2与API Key、版本控制方式)。
Troubleshooting
故障排除
- User provides a vague requirement: Create a baseline API with the most common REST patterns and flag explicit decisions as open questions.
- Conflicting HTTP semantics: If the user requests a non-REST pattern (e.g., ), explain why REST prohibits it and propose the RESTful equivalent.
GET /deleteUser - Polymorphic schemas too complex: Use without discriminator for fewer than 3 variants; add discriminator only when runtime type detection is needed.
oneOf - Too many endpoints: The API scope may be too broad — suggest grouping related resources and delivering a phased spec.
- User wants JSON Schema instead of OpenAPI: Clarify that OpenAPI is the standard for API contracts and can embed JSON Schema; produce OpenAPI but note that the schemas can be extracted as standalone JSON Schema.
- 用户需求模糊: 使用最常见的REST模式创建基准API,并将明确的决策标记为待确认问题。
- HTTP语义冲突: 如果用户请求非REST模式(例如),解释REST为何禁止此类操作,并提出符合REST标准的替代方案。
GET /deleteUser - 多态模式过于复杂: 变体少于3个时,使用不带鉴别器的;仅当运行时类型检测需要时才添加鉴别器。
oneOf - 端点过多: API范围可能过于宽泛——建议对相关资源进行分组,并分阶段交付规范。
- 用户需要JSON Schema而非OpenAPI: 说明OpenAPI是API契约的标准,且可嵌入JSON Schema;生成OpenAPI规范,但需注明其中的模式可提取为独立的JSON Schema。