api-designer
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Designer
API 设计器
Protocols
协议
!
!
!
!
!
cat skills/_shared/protocols/ux-protocol.md 2>/dev/null || truecat skills/_shared/protocols/input-validation.md 2>/dev/null || truecat skills/_shared/protocols/tool-efficiency.md 2>/dev/null || truecat .production-grade.yaml 2>/dev/null || echo "No config — using defaults"cat .forgewright/codebase-context.md 2>/dev/null || trueFallback (if protocols not loaded): Use notify_user with options (never open-ended), "Chat about this" last, recommended first. Work continuously. Print progress constantly. Validate inputs before starting — classify missing as Critical (stop), Degraded (warn, continue partial), or Optional (skip silently). Use parallel tool calls for independent reads. Use view_file_outline before full Read.
!
!
!
!
!
cat skills/_shared/protocols/ux-protocol.md 2>/dev/null || truecat skills/_shared/protocols/input-validation.md 2>/dev/null || truecat skills/_shared/protocols/tool-efficiency.md 2>/dev/null || truecat .production-grade.yaml 2>/dev/null || echo "No config — using defaults"cat .forgewright/codebase-context.md 2>/dev/null || true备选方案(若协议未加载): 使用带有选项的notify_user(绝不采用开放式选项),将“就此展开讨论”放在最后,优先推荐方案。持续推进工作,不断输出进度。开始前验证输入——将缺失内容分为三类:关键项(停止工作)、降级项(发出警告,继续部分工作)、可选项(静默跳过)。对独立读取操作使用并行工具调用。在完整读取前先使用view_file_outline。
Engagement Mode
协作模式
!
cat .forgewright/settings.md 2>/dev/null || echo "No settings — using Standard"| Mode | Behavior |
|---|---|
| Express | Fully autonomous. Design APIs using best practices. Report decisions in output. |
| Standard | Surface API style choice (REST vs GraphQL vs gRPC), pagination strategy, and versioning approach. Auto-resolve everything else. |
| Thorough | Present full API design document before implementation. Walk through resource modeling and endpoint design. Show error code taxonomy. Ask about consumer needs. |
| Meticulous | Walk through each resource individually. User reviews endpoint signatures, request/response schemas, and error responses. Show API mock for consumer validation. |
!
cat .forgewright/settings.md 2>/dev/null || echo "No settings — using Standard"| 模式 | 行为 |
|---|---|
| 快速模式 | 完全自主操作,采用最佳实践设计API,在输出中说明决策依据。 |
| 标准模式 | 明确API风格选择(REST vs GraphQL vs gRPC)、分页策略和版本控制方案,自动解决其他所有问题。 |
| 全面模式 | 在实施前提交完整的API设计文档,讲解资源建模和端点设计,展示错误代码分类体系,并询问消费者需求。 |
| 精细模式 | 逐个讲解每个资源,由用户审核端点签名、请求/响应架构和错误响应,提供API模拟版本供消费者验证。 |
Brownfield Awareness
遗留系统适配
If exists and mode is :
.forgewright/codebase-context.mdbrownfield- READ existing API patterns first — understand current URL structure, naming conventions, error format
- MATCH existing conventions — if they use camelCase, don't switch to snake_case
- BACKWARD COMPATIBLE — new endpoints only. Never break existing consumers
- Document existing patterns — capture conventions in the API style guide before extending
若存在且模式为:
.forgewright/codebase-context.mdbrownfield- 优先读取现有API模式——理解当前URL结构、命名规范、错误格式
- 匹配现有规范——若使用camelCase,不要切换为snake_case
- 保持向后兼容——仅新增端点,绝不影响现有消费者
- 记录现有模式——在扩展前将规范纳入API风格指南
Overview
概述
Dedicated API design pipeline: from domain modeling through resource design, endpoint specification, error taxonomy, and API documentation. Produces OpenAPI/AsyncAPI specs and API style guides. Works upstream of Phase 4 for API-heavy projects, or standalone when designing individual APIs.
solution-architect专用API设计流程:从领域建模到资源设计、端点规范、错误分类体系及API文档生成。可产出OpenAPI/AsyncAPI规范和API风格指南。在API密集型项目中,可作为第四阶段的前置工作,也可独立用于单个API的设计。
solution-architectInput Classification
输入分类
| Category | Inputs | Behavior if Missing |
|---|---|---|
| Critical | Domain entities, user stories, or feature requirements | STOP — cannot design API without knowing the domain |
| Degraded | Existing API patterns (brownfield), consumer requirements, scale expectations | WARN — will design using best practices as defaults |
| Optional | Authentication strategy (from | Continue — use sensible defaults |
| 类别 | 输入内容 | 缺失时的行为 |
|---|---|---|
| 关键项 | 领域实体、用户故事或功能需求 | 停止工作——不了解领域则无法设计API |
| 降级项 | 现有API模式(遗留系统)、消费者需求、规模预期 | 发出警告——将采用最佳实践作为默认方案进行设计 |
| 可选项 | 认证策略(来自 | 继续工作——使用合理的默认值 |
Process Flow
流程步骤
dot
digraph api_designer {
rankdir=TB;
"API Request" [shape=doublecircle];
"Phase 1: Domain Modeling" [shape=box];
"Phase 2: Resource Design" [shape=box];
"Phase 3: Endpoint Specification" [shape=box];
"Phase 4: Error & Edge Cases" [shape=box];
"Phase 5: Documentation & Governance" [shape=box];
"Done" [shape=doublecircle];
"API Request" -> "Phase 1: Domain Modeling";
"Phase 1: Domain Modeling" -> "Phase 2: Resource Design";
"Phase 2: Resource Design" -> "Phase 3: Endpoint Specification";
"Phase 3: Endpoint Specification" -> "Phase 4: Error & Edge Cases";
"Phase 4: Error & Edge Cases" -> "Phase 5: Documentation & Governance";
"Phase 5: Documentation & Governance" -> "Done";
}dot
digraph api_designer {
rankdir=TB;
"API Request" [shape=doublecircle];
"Phase 1: Domain Modeling" [shape=box];
"Phase 2: Resource Design" [shape=box];
"Phase 3: Endpoint Specification" [shape=box];
"Phase 4: Error & Edge Cases" [shape=box];
"Phase 5: Documentation & Governance" [shape=box];
"Done" [shape=doublecircle];
"API Request" -> "Phase 1: Domain Modeling";
"Phase 1: Domain Modeling" -> "Phase 2: Resource Design";
"Phase 2: Resource Design" -> "Phase 3: Endpoint Specification";
"Phase 3: Endpoint Specification" -> "Phase 4: Error & Edge Cases";
"Phase 4: Error & Edge Cases" -> "Phase 5: Documentation & Governance";
"Phase 5: Documentation & Governance" -> "Done";
}Parallel Execution
并行执行
After Phase 2 (Resource Design), Phases 3-4 can run in parallel:
python
Execute sequentially: Design REST/GraphQL endpoint specifications following Phase 3. Write to api/openapi/.
Execute sequentially: Design error taxonomy and edge cases following Phase 4. Write to api/errors/.Wait for both, then run Phase 5 (Documentation) sequentially.
完成第二阶段(资源设计)后,第三至第四阶段可并行执行:
python
Execute sequentially: Design REST/GraphQL endpoint specifications following Phase 3. Write to api/openapi/.
Execute sequentially: Design error taxonomy and edge cases following Phase 4. Write to api/errors/.等待两者完成后,再依次执行第五阶段(文档生成)。
Phase 1 — Domain Modeling
第一阶段——领域建模
Goal: Identify API resources from domain entities and their relationships.
Actions:
-
Extract entities from BRD/domain (User, Order, Product, etc.)
-
Identify relationships: one-to-one, one-to-many, many-to-many
-
Classify entities:
- Primary resources — have their own endpoints (,
/users)/orders - Sub-resources — nested under parent ()
/orders/{id}/items - Lookup/reference — read-only, rarely change (,
/countries)/categories - Action resources — represent operations, not data ()
/orders/{id}/cancel
- Primary resources — have their own endpoints (
-
Map CRUD operations to HTTP methods (standard REST mapping, useheader for POST idempotency)
Idempotency-Key
Output: Entity-relationship diagram, resource hierarchy.
目标: 从领域实体及其关系中识别API资源。
操作:
-
从业务需求文档/领域中提取实体(如User、Order、Product等)
-
识别关系:一对一、一对多、多对多
-
对实体进行分类:
- 主资源——拥有独立端点(、
/users)/orders - 子资源——嵌套在父资源下()
/orders/{id}/items - 查询/引用资源——只读,极少变更(、
/countries)/categories - 操作资源——代表操作而非数据()
/orders/{id}/cancel
- 主资源——拥有独立端点(
-
将CRUD操作映射到HTTP方法(标准REST映射,对POST幂等性使用请求头)
Idempotency-Key
输出: 实体关系图、资源层级结构。
Phase 2 — Resource Design
第二阶段——资源设计
Goal: Design URL structure, naming conventions, and resource representation.
URL naming rules:
- Plural nouns for collections: ,
/users(not/orders,/user)/order - Kebab-case for multi-word: (not
/line-itemsor/lineItems)/line_items - No verbs in URLs: is a POST action (not
/orders/{id}/cancel)/cancelOrder - Max 3 levels of nesting: ✓,
/users/{id}/orders✗/users/{id}/orders/{oid}/items/{iid}/reviews - Use query params for filtering:
/orders?status=pending&sort=-created_at
Request/Response conventions:
- Request bodies: camelCase JSON (matches JavaScript convention)
- Response envelopes: consistent wrapper structure:
json
{ "data": { ... }, // Single resource or array "meta": { // Pagination, totals "total": 150, "page": 1, "perPage": 20 }, "links": { // HATEOAS navigation "self": "/api/v1/orders?page=1", "next": "/api/v1/orders?page=2" } }
Pagination strategies:
| Strategy | Pros | Cons | Use When |
|---|---|---|---|
| Cursor-based | Consistent with concurrent writes, efficient | Can't jump to page N | Default for production APIs. Most common pattern. |
| Offset/Limit | Simple, familiar, can jump to any page | Inconsistent with concurrent writes, slow at large offsets | Admin dashboards, internal tools |
| Keyset | Efficient for large datasets, consistent | Requires sortable unique column | Time-series data, logs |
Default: cursor-based pagination with and in response.
?cursor=abc123&limit=20next_cursorGate: Validate resource inventory covers all domain entities before proceeding.
Output: URL inventory, request/response schemas.
目标: 设计URL结构、命名规范和资源表示方式。
URL命名规则:
- 集合使用复数名词:、
/users(而非/orders、/user)/order - 多词使用短横线分隔:(而非
/line-items或/lineItems)/line_items - URL中不使用动词:是POST操作(而非
/orders/{id}/cancel)/cancelOrder - 嵌套最多3级:✓,
/users/{id}/orders✗/users/{id}/orders/{oid}/items/{iid}/reviews - 使用查询参数进行过滤:
/orders?status=pending&sort=-created_at
请求/响应规范:
- 请求体:采用camelCase格式的JSON(与JavaScript规范一致)
- 响应信封:统一的包装结构:
json
{ "data": { ... }, // 单个资源或数组 "meta": { // 分页、总数信息 "total": 150, "page": 1, "perPage": 20 }, "links": { // HATEOAS导航 "self": "/api/v1/orders?page=1", "next": "/api/v1/orders?page=2" } }
分页策略:
| 策略 | 优势 | 劣势 | 使用场景 |
|---|---|---|---|
| 基于游标 | 与并发写入兼容,性能高效 | 无法直接跳转到第N页 | 生产API的默认方案,最常用模式 |
| 偏移量/限制 | 简单易懂,可跳转到任意页面 | 与并发写入不兼容,大偏移量时性能慢 | 管理后台、内部工具 |
| 基于键集 | 大数据集下性能高效,一致性好 | 需要可排序的唯一列 | 时间序列数据、日志 |
默认方案: 基于游标的分页,使用,响应中返回。
?cursor=abc123&limit=20next_cursor校验门: 确认资源清单覆盖所有领域实体后再进入下一阶段。
输出: URL清单、请求/响应架构。
Phase 3 — Endpoint Specification
第三阶段——端点规范
Goal: Write complete endpoint specifications in OpenAPI 3.1 format.
Per-endpoint requirements:
- Summary — one-line description
- Description — detailed behavior, business rules, side effects
- Parameters — path, query, header params with types and validation
- Request body — JSON schema with required/optional fields, examples
- Responses — all status codes (200, 201, 400, 401, 403, 404, 409, 422, 500) with schemas
- Authentication — which auth method (Bearer token, API key, OAuth2 scope)
- Rate limiting — per-endpoint limits if different from default
- Idempotency — whether is supported/required
Idempotency-Key
Standard headers:
| Header | Direction | Purpose |
|---|---|---|
| Request | Bearer token or API key |
| Request | Client-generated request tracking ID |
| Request | Prevent duplicate mutations |
| Both | |
| Response | Requests allowed per window |
| Response | Requests remaining in window |
| Response | Window reset time (Unix timestamp) |
| Response | Echo or server-generated trace ID |
Versioning strategy:
- URL path versioning (recommended): ,
/api/v1/users/api/v2/users - Version in URL is explicit, cacheable, and easy to route
- Support N-1 version minimum (current + previous)
- Deprecation: header + 6 months notice + migration guide
Sunset
Gate: Run OpenAPI linter on generated spec before proceeding.
Output: OpenAPI 3.1 spec files in .
api/openapi/目标: 以OpenAPI 3.1格式编写完整的端点规范。
每个端点的要求:
- 摘要——一行描述
- 详细说明——行为细节、业务规则、副作用
- 参数——路径、查询、请求头参数,包含类型和校验规则
- 请求体——JSON架构,包含必填/可选字段及示例
- 响应——所有状态码(200、201、400、401、403、404、409、422、500)及对应架构
- 认证——使用的认证方式(Bearer令牌、API密钥、OAuth2权限范围)
- 速率限制——若与默认值不同,需注明每个端点的限制
- 幂等性——是否支持/要求
Idempotency-Key
标准请求头:
| 请求头 | 方向 | 用途 |
|---|---|---|
| 请求 | Bearer令牌或API密钥 |
| 请求 | 客户端生成的请求跟踪ID |
| 请求 | 防止重复变更操作 |
| 双向 | |
| 响应 | 窗口期内允许的请求次数 |
| 响应 | 窗口期内剩余的请求次数 |
| 响应 | 窗口期重置时间(Unix时间戳) |
| 响应 | 回显或服务端生成的跟踪ID |
版本控制策略:
- URL路径版本控制(推荐):、
/api/v1/users/api/v2/users - URL中的版本清晰明确,可缓存,易于路由
- 至少支持N-1版本(当前版本+上一版本)
- 废弃流程:请求头 + 6个月通知 + 迁移指南
Sunset
校验门: 对生成的规范运行OpenAPI校验器后再进入下一阶段。
输出: 存储在中的OpenAPI 3.1规范文件。
api/openapi/Phase 4 — Error Design & Edge Cases
第四阶段——错误设计与边界场景
Goal: Design a comprehensive, consistent error handling system.
Standard error response:
json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "The request body contains invalid fields.",
"details": [
{
"field": "email",
"issue": "must be a valid email address",
"value": "not-an-email"
}
],
"requestId": "req_abc123",
"documentation": "https://docs.example.com/errors/VALIDATION_ERROR"
}
}Error code taxonomy:
| HTTP Status | Error Code | When |
|---|---|---|
| 400 | | Malformed JSON, missing required params |
| 400 | | Field validation failures (with |
| 401 | | Missing or invalid auth token |
| 403 | | Valid auth but insufficient permissions |
| 404 | | Resource doesn't exist |
| 409 | | Duplicate creation, stale update (optimistic locking) |
| 422 | | Valid format but business rule violation |
| 429 | | Too many requests (include |
| 500 | | Unexpected server error (never expose stack traces) |
| 503 | | Temporary outage (include |
Edge cases to design for:
- Concurrent updates (optimistic locking with /
ETag)If-Match - Partial failures in batch operations (return per-item results)
- Large payloads (413 with max size documentation)
- Slow responses (timeout handling, async operations with 202 + status endpoint)
- Deleted resources (410 Gone vs 404 Not Found)
Output: Error taxonomy document, error response schemas.
目标: 设计全面、一致的错误处理系统。
标准错误响应:
json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "请求体包含无效字段。",
"details": [
{
"field": "email",
"issue": "必须是有效的邮箱地址",
"value": "not-an-email"
}
],
"requestId": "req_abc123",
"documentation": "https://docs.example.com/errors/VALIDATION_ERROR"
}
}错误代码分类体系:
| HTTP状态码 | 错误代码 | 使用场景 |
|---|---|---|
| 400 | | JSON格式错误、缺失必填参数 |
| 400 | | 字段校验失败(包含 |
| 401 | | 缺失或无效的认证令牌 |
| 403 | | 认证有效但权限不足 |
| 404 | | 资源不存在 |
| 409 | | 重复创建、过期更新(乐观锁) |
| 422 | | 格式有效但违反业务规则 |
| 429 | | 请求次数过多(包含 |
| 500 | | 意外服务错误(绝不暴露堆栈跟踪) |
| 503 | | 临时服务中断(包含 |
需要设计的边界场景:
- 并发更新(使用/
ETag实现乐观锁)If-Match - 批量操作中的部分失败(返回每个条目的结果)
- 大负载(返回413并附带最大容量文档)
- 慢响应(超时处理、异步操作返回202 + 状态端点)
- 已删除资源(410 Gone vs 404 Not Found)
输出: 错误分类文档、错误响应架构。
Phase 5 — Documentation & Governance
第五阶段——文档与治理
Goal: Generate API documentation and governance rules.
API style guide (write to ):
docs/api/style-guide.md- Naming conventions (URL, fields, query params)
- Pagination standard
- Error format standard
- Authentication patterns
- Versioning policy
- Deprecation process
- Breaking vs non-breaking changes
Breaking change definition:
| Breaking ✗ | Non-Breaking ✓ |
|---|---|
| Removing a field from response | Adding a new optional field to response |
| Changing a field type | Adding a new endpoint |
| Removing an endpoint | Adding a new optional query parameter |
| Making an optional field required | Adding a new error code |
| Changing URL structure | Adding a new header |
API changelog (append to ):
CHANGELOG.md- Every API change logged with version, date, breaking/non-breaking, and migration guide
Output: API style guide, governance rules, changelog entries.
目标: 生成API文档和治理规则。
API风格指南(写入):
docs/api/style-guide.md- 命名规范(URL、字段、查询参数)
- 分页标准
- 错误格式标准
- 认证模式
- 版本控制策略
- 废弃流程
- 破坏性变更vs非破坏性变更
破坏性变更定义:
| 破坏性变更 ✗ | 非破坏性变更 ✓ |
|---|---|
| 从响应中移除字段 | 向响应中新增可选字段 |
| 变更字段类型 | 新增端点 |
| 移除端点 | 新增可选查询参数 |
| 将可选字段设为必填 | 新增错误代码 |
| 变更URL结构 | 新增请求头 |
API变更日志(追加到):
CHANGELOG.md- 所有API变更需记录版本、日期、是否为破坏性变更及迁移指南
输出: API风格指南、治理规则、变更日志条目。
Output Structure
输出结构
Project Root
项目根目录
api/
├── openapi/
│ ├── openapi.yaml # Main OpenAPI 3.1 spec
│ └── components/
│ ├── schemas/ # Reusable JSON schemas
│ ├── responses/ # Standard error responses
│ └── parameters/ # Common query parameters
├── errors/
│ └── error-taxonomy.md # Error code reference
└── graphql/ # (if GraphQL chosen)
├── schema.graphql
└── resolvers.md
docs/api/
├── style-guide.md # API conventions and standards
├── versioning-policy.md # How versions are managed
└── migration-guides/ # Per-version migration docsapi/
├── openapi/
│ ├── openapi.yaml # 主OpenAPI 3.1规范
│ └── components/
│ ├── schemas/ # 可复用JSON架构
│ ├── responses/ # 标准错误响应
│ └── parameters/ # 通用查询参数
├── errors/
│ └── error-taxonomy.md # 错误代码参考文档
└── graphql/ # (若选择GraphQL)
├── schema.graphql
└── resolvers.md
docs/api/
├── style-guide.md # API规范与标准
├── versioning-policy.md # 版本管理策略
└── migration-guides/ # 各版本迁移文档Workspace
工作区
.forgewright/api-designer/
├── domain-model.md # Entity relationship analysis
├── resource-inventory.md # URL inventory with methods
└── design-decisions.md # API design rationale.forgewright/api-designer/
├── domain-model.md # 实体关系分析
├── resource-inventory.md # URL清单及对应方法
└── design-decisions.md # API设计依据Common Mistakes
常见错误
| Mistake | Fix |
|---|---|
Verbs in URLs ( | Use nouns + HTTP methods: |
Inconsistent naming ( | Pick one convention (camelCase recommended) and enforce everywhere |
| No pagination on list endpoints | EVERY list endpoint must paginate. Default: cursor-based, 20 items. |
| Generic error messages ("Something went wrong") | Specific codes + details: |
| Exposing internal IDs (auto-increment) | Use UUIDs or opaque IDs. Auto-increment leaks data volume. |
| No versioning from the start | Add |
| Inconsistent response envelope | Same wrapper for all endpoints: |
| Missing idempotency for mutations | Support |
| Deeply nested URLs (> 3 levels) | Flatten with query params: |
| No rate limiting | Every API needs rate limits. Document them. Return |
| 错误 | 修复方案 |
|---|---|
URL中使用动词( | 使用名词+HTTP方法: |
命名不一致( | 选择一种规范(推荐camelCase)并全局执行 |
| 列表端点未实现分页 | 所有列表端点必须分页,默认采用基于游标分页,每页20条 |
| 通用错误信息(“发生未知错误”) | 使用具体代码+详细信息:如 |
| 暴露内部ID(自增ID) | 使用UUID或不透明ID,自增ID会泄露数据量信息 |
| 初始阶段未做版本控制 | 从第一天起就添加 |
| 响应信封不一致 | 所有端点使用统一包装: |
| 变更操作未实现幂等性 | 对POST/PATCH端点支持 |
| URL嵌套过深(超过3级) | 使用查询参数扁平化: |
| 未设置速率限制 | 所有API都需要速率限制,需记录相关规则,返回 |