api-designer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API Designer

API 设计器

Protocols

协议

!
cat skills/_shared/protocols/ux-protocol.md 2>/dev/null || true
!
cat skills/_shared/protocols/input-validation.md 2>/dev/null || true
!
cat skills/_shared/protocols/tool-efficiency.md 2>/dev/null || true
!
cat .production-grade.yaml 2>/dev/null || echo "No config — using defaults"
!
cat .forgewright/codebase-context.md 2>/dev/null || true
Fallback (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 || true
!
cat skills/_shared/protocols/input-validation.md 2>/dev/null || true
!
cat skills/_shared/protocols/tool-efficiency.md 2>/dev/null || true
!
cat .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"
ModeBehavior
ExpressFully autonomous. Design APIs using best practices. Report decisions in output.
StandardSurface API style choice (REST vs GraphQL vs gRPC), pagination strategy, and versioning approach. Auto-resolve everything else.
ThoroughPresent full API design document before implementation. Walk through resource modeling and endpoint design. Show error code taxonomy. Ask about consumer needs.
MeticulousWalk 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
.forgewright/codebase-context.md
exists and mode is
brownfield
:
  • 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.md
存在且模式为
brownfield
  • 优先读取现有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
solution-architect
Phase 4 for API-heavy projects, or standalone when designing individual APIs.
专用API设计流程:从领域建模到资源设计、端点规范、错误分类体系及API文档生成。可产出OpenAPI/AsyncAPI规范和API风格指南。在API密集型项目中,可作为
solution-architect
第四阶段的前置工作,也可独立用于单个API的设计。

Input Classification

输入分类

CategoryInputsBehavior if Missing
CriticalDomain entities, user stories, or feature requirementsSTOP — cannot design API without knowing the domain
DegradedExisting API patterns (brownfield), consumer requirements, scale expectationsWARN — will design using best practices as defaults
OptionalAuthentication strategy (from
solution-architect
), rate limit requirements, compliance constraints
Continue — use sensible defaults
类别输入内容缺失时的行为
关键项领域实体、用户故事或功能需求停止工作——不了解领域则无法设计API
降级项现有API模式(遗留系统)、消费者需求、规模预期发出警告——将采用最佳实践作为默认方案进行设计
可选项认证策略(来自
solution-architect
)、速率限制要求、合规约束
继续工作——使用合理的默认值

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:
  1. Extract entities from BRD/domain (User, Order, Product, etc.)
  2. Identify relationships: one-to-one, one-to-many, many-to-many
  3. 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
      )
  4. Map CRUD operations to HTTP methods (standard REST mapping, use
    Idempotency-Key
    header for POST idempotency)
Output: Entity-relationship diagram, resource hierarchy.

目标: 从领域实体及其关系中识别API资源。
操作:
  1. 从业务需求文档/领域中提取实体(如User、Order、Product等)
  2. 识别关系:一对一、一对多、多对多
  3. 对实体进行分类:
    • 主资源——拥有独立端点(
      /users
      /orders
    • 子资源——嵌套在父资源下(
      /orders/{id}/items
    • 查询/引用资源——只读,极少变更(
      /countries
      /categories
    • 操作资源——代表操作而非数据(
      /orders/{id}/cancel
  4. 将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
    ,
    /orders
    (not
    /user
    ,
    /order
    )
  • Kebab-case for multi-word:
    /line-items
    (not
    /lineItems
    or
    /line_items
    )
  • No verbs in URLs:
    /orders/{id}/cancel
    is a POST action (not
    /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:
StrategyProsConsUse When
Cursor-basedConsistent with concurrent writes, efficientCan't jump to page NDefault for production APIs. Most common pattern.
Offset/LimitSimple, familiar, can jump to any pageInconsistent with concurrent writes, slow at large offsetsAdmin dashboards, internal tools
KeysetEfficient for large datasets, consistentRequires sortable unique columnTime-series data, logs
Default: cursor-based pagination with
?cursor=abc123&limit=20
and
next_cursor
in response.
Gate: 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中不使用动词:
    /orders/{id}/cancel
    是POST操作(而非
    /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=20
,响应中返回
next_cursor
校验门: 确认资源清单覆盖所有领域实体后再进入下一阶段。
输出: URL清单、请求/响应架构。

Phase 3 — Endpoint Specification

第三阶段——端点规范

Goal: Write complete endpoint specifications in OpenAPI 3.1 format.
Per-endpoint requirements:
  1. Summary — one-line description
  2. Description — detailed behavior, business rules, side effects
  3. Parameters — path, query, header params with types and validation
  4. Request body — JSON schema with required/optional fields, examples
  5. Responses — all status codes (200, 201, 400, 401, 403, 404, 409, 422, 500) with schemas
  6. Authentication — which auth method (Bearer token, API key, OAuth2 scope)
  7. Rate limiting — per-endpoint limits if different from default
  8. Idempotency — whether
    Idempotency-Key
    is supported/required
Standard headers:
HeaderDirectionPurpose
Authorization
RequestBearer token or API key
X-Request-ID
RequestClient-generated request tracking ID
X-Idempotency-Key
RequestPrevent duplicate mutations
Content-Type
Both
application/json
X-RateLimit-Limit
ResponseRequests allowed per window
X-RateLimit-Remaining
ResponseRequests remaining in window
X-RateLimit-Reset
ResponseWindow reset time (Unix timestamp)
X-Request-ID
ResponseEcho 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:
    Sunset
    header + 6 months notice + migration guide
Gate: Run OpenAPI linter on generated spec before proceeding.
Output: OpenAPI 3.1 spec files in
api/openapi/
.

目标: 以OpenAPI 3.1格式编写完整的端点规范。
每个端点的要求:
  1. 摘要——一行描述
  2. 详细说明——行为细节、业务规则、副作用
  3. 参数——路径、查询、请求头参数,包含类型和校验规则
  4. 请求体——JSON架构,包含必填/可选字段及示例
  5. 响应——所有状态码(200、201、400、401、403、404、409、422、500)及对应架构
  6. 认证——使用的认证方式(Bearer令牌、API密钥、OAuth2权限范围)
  7. 速率限制——若与默认值不同,需注明每个端点的限制
  8. 幂等性——是否支持/要求
    Idempotency-Key
标准请求头:
请求头方向用途
Authorization
请求Bearer令牌或API密钥
X-Request-ID
请求客户端生成的请求跟踪ID
X-Idempotency-Key
请求防止重复变更操作
Content-Type
双向
application/json
X-RateLimit-Limit
响应窗口期内允许的请求次数
X-RateLimit-Remaining
响应窗口期内剩余的请求次数
X-RateLimit-Reset
响应窗口期重置时间(Unix时间戳)
X-Request-ID
响应回显或服务端生成的跟踪ID
版本控制策略:
  • URL路径版本控制(推荐):
    /api/v1/users
    /api/v2/users
  • URL中的版本清晰明确,可缓存,易于路由
  • 至少支持N-1版本(当前版本+上一版本)
  • 废弃流程:
    Sunset
    请求头 + 6个月通知 + 迁移指南
校验门: 对生成的规范运行OpenAPI校验器后再进入下一阶段。
输出: 存储在
api/openapi/
中的OpenAPI 3.1规范文件。

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 StatusError CodeWhen
400
BAD_REQUEST
Malformed JSON, missing required params
400
VALIDATION_ERROR
Field validation failures (with
details
array)
401
UNAUTHORIZED
Missing or invalid auth token
403
FORBIDDEN
Valid auth but insufficient permissions
404
NOT_FOUND
Resource doesn't exist
409
CONFLICT
Duplicate creation, stale update (optimistic locking)
422
UNPROCESSABLE
Valid format but business rule violation
429
RATE_LIMITED
Too many requests (include
Retry-After
header)
500
INTERNAL_ERROR
Unexpected server error (never expose stack traces)
503
SERVICE_UNAVAILABLE
Temporary outage (include
Retry-After
header)
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
BAD_REQUEST
JSON格式错误、缺失必填参数
400
VALIDATION_ERROR
字段校验失败(包含
details
数组)
401
UNAUTHORIZED
缺失或无效的认证令牌
403
FORBIDDEN
认证有效但权限不足
404
NOT_FOUND
资源不存在
409
CONFLICT
重复创建、过期更新(乐观锁)
422
UNPROCESSABLE
格式有效但违反业务规则
429
RATE_LIMITED
请求次数过多(包含
Retry-After
请求头)
500
INTERNAL_ERROR
意外服务错误(绝不暴露堆栈跟踪)
503
SERVICE_UNAVAILABLE
临时服务中断(包含
Retry-After
请求头)
需要设计的边界场景:
  • 并发更新(使用
    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 responseAdding a new optional field to response
Changing a field typeAdding a new endpoint
Removing an endpointAdding a new optional query parameter
Making an optional field requiredAdding a new error code
Changing URL structureAdding 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 docs
api/
├── 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

常见错误

MistakeFix
Verbs in URLs (
/getUser
,
/createOrder
)
Use nouns + HTTP methods:
GET /users/{id}
,
POST /orders
Inconsistent naming (
userId
vs
user_id
vs
UserID
)
Pick one convention (camelCase recommended) and enforce everywhere
No pagination on list endpointsEVERY list endpoint must paginate. Default: cursor-based, 20 items.
Generic error messages ("Something went wrong")Specific codes + details:
VALIDATION_ERROR
with field-level issues
Exposing internal IDs (auto-increment)Use UUIDs or opaque IDs. Auto-increment leaks data volume.
No versioning from the startAdd
/v1/
from day one. Retrofitting is painful.
Inconsistent response envelopeSame wrapper for all endpoints:
{ data, meta, links }
Missing idempotency for mutationsSupport
Idempotency-Key
header for POST/PATCH endpoints
Deeply nested URLs (> 3 levels)Flatten with query params:
/items?orderId=123
instead of
/users/1/orders/2/items
No rate limitingEvery API needs rate limits. Document them. Return
429
with
Retry-After
.
错误修复方案
URL中使用动词(
/getUser
/createOrder
使用名词+HTTP方法:
GET /users/{id}
POST /orders
命名不一致(
userId
vs
user_id
vs
UserID
选择一种规范(推荐camelCase)并全局执行
列表端点未实现分页所有列表端点必须分页,默认采用基于游标分页,每页20条
通用错误信息(“发生未知错误”)使用具体代码+详细信息:如
VALIDATION_ERROR
附带字段级问题
暴露内部ID(自增ID)使用UUID或不透明ID,自增ID会泄露数据量信息
初始阶段未做版本控制从第一天起就添加
/v1/
,后期再补版本控制会非常麻烦
响应信封不一致所有端点使用统一包装:
{ data, meta, links }
变更操作未实现幂等性对POST/PATCH端点支持
Idempotency-Key
请求头
URL嵌套过深(超过3级)使用查询参数扁平化:
/items?orderId=123
而非
/users/1/orders/2/items
未设置速率限制所有API都需要速率限制,需记录相关规则,返回
429
并附带
Retry-After