api-design

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API Design

API设计

Overview

概述

Structured API endpoint design through guided discovery. Produces consistent, well-documented API designs with OpenAPI/Swagger specifications. Covers resource modeling, authentication, pagination, error handling, and versioning — ensuring consumer-centric design before any implementation begins.
Announce at start: "I'm using the api-design skill to design the API."
通过引导式调研完成结构化的API端点设计,输出符合OpenAPI/Swagger规范、一致且文档完备的API设计方案,覆盖资源建模、鉴权、分页、错误处理和版本控制,确保在启动任何开发工作前就完成以调用方为中心的设计。
开篇声明: "我将使用api-design技能来设计API。"

Phase 1: Discovery

阶段1:需求调研

Ask these questions ONE AT A TIME:
请逐个询问以下问题:

Resource Questions

资源相关问题

#QuestionWhat It Determines
1What entities/resources does this API manage?Resource naming
2What are the relationships between them?Nested routes, includes
3What operations are needed for each? (CRUD, search, batch)HTTP methods, endpoints
#问题作用
1该API管理哪些实体/资源?资源命名
2资源之间存在什么关系?嵌套路由、关联字段
3每个资源需要支持哪些操作?(CRUD、搜索、批量操作)HTTP方法、端点定义

Consumer Questions

调用方相关问题

#QuestionWhat It Determines
4Who will consume this API? (frontend, mobile, third-party, internal)Response shape, auth model
5What authentication/authorization is needed?Security scheme
6What rate limits or quotas apply?Rate limiting headers
#问题作用
4哪些角色会调用该API?(前端、移动端、第三方、内部服务)响应结构、鉴权模型
5需要什么样的身份认证/授权机制?安全方案
6适用什么限流规则或配额?限流响应头

Constraint Questions

约束条件相关问题

#QuestionWhat It Determines
7REST, GraphQL, or tRPC?API paradigm
8Versioning strategy? (URL path, header, query param)URL structure
9Pagination approach? (cursor, offset, keyset)List response shape
10Existing API conventions in the codebase?Consistency constraints
#问题作用
7选用REST、GraphQL还是tRPC?API开发范式
8版本控制策略是什么?(URL路径、请求头、查询参数)URL结构
9分页方案是什么?(游标、偏移量、键集)列表响应结构
10代码库中现有API规范是什么?一致性约束

API Paradigm Decision Table

API范式选型对照表

FactorChoose RESTChoose GraphQLChoose tRPC
ConsumersMultiple, diverseFrontend-heavy, flexible queriesTypeScript monorepo
Caching needsStrong (HTTP caching)Moderate (client-side)Low (internal only)
Data shapePredictable, resource-orientedNested, variable-shapeType-safe RPC
Team familiarityUniversalRequires schema knowledgeRequires TypeScript
Real-time needsWebSocket addonSubscriptions built-inSubscription support
STOP after discovery — present a summary of resources, operations, and constraints. Get confirmation before designing endpoints.
考量因素选REST选GraphQL选tRPC
调用方情况多类型、多样化调用前端为主、需要灵活查询TypeScript单体代码库
缓存需求强需求(HTTP缓存)中等需求(客户端缓存)低需求(仅内部调用)
数据结构可预测、面向资源嵌套、结构可变类型安全的RPC
团队熟悉度通用易上手需要掌握schema知识需要掌握TypeScript
实时性需求需要WebSocket扩展内置订阅功能支持订阅
调研阶段结束后暂停 —— 输出资源、操作和约束条件的总结,获得确认后再开始设计端点。

Phase 2: Design Endpoints

阶段2:设计端点

For each endpoint, define:
markdown
undefined
每个端点需要定义以下内容:
markdown
undefined

[METHOD] /api/v1/[resource]

[METHOD] /api/v1/[resource]

Purpose: [what this endpoint does]
Request:
  • Headers:
    Authorization: Bearer <token>
  • Query params:
    ?page=1&limit=20&sort=created_at:desc
  • Body:
    json
    {
      "field": "type — description"
    }
Response (200):
json
{
  "data": [...],
  "meta": { "total": 100, "page": 1, "limit": 20 }
}
Error Responses:
StatusCodeDescription
400VALIDATION_ERRORInvalid request body
401UNAUTHORIZEDMissing or invalid token
404NOT_FOUNDResource doesn't exist
409CONFLICTResource already exists
Authorization: [who can access this]
undefined
用途: [该端点的功能说明]
请求:
  • 请求头:
    Authorization: Bearer <token>
  • 查询参数:
    ?page=1&limit=20&sort=created_at:desc
  • 请求体:
    json
    {
      "field": "type — description"
    }
响应 (200):
json
{
  "data": [...],
  "meta": { "total": 100, "page": 1, "limit": 20 }
}
错误响应:
状态码错误码说明
400VALIDATION_ERROR请求体校验失败
401UNAUTHORIZED缺失或无效token
404NOT_FOUND资源不存在
409CONFLICT资源已存在
授权规则: [可访问该端点的角色说明]
undefined

HTTP Method Decision Table

HTTP方法选型对照表

OperationMethodStatus (success)Idempotent
List resourcesGET200Yes
Get single resourceGET200Yes
Create resourcePOST201No
Full replacePUT200Yes
Partial updatePATCH200No
Delete resourceDELETE204Yes
Bulk createPOST201No
Search (complex)POST200Yes (safe)
操作方法成功状态码幂等性
列举资源GET200
获取单个资源GET200
创建资源POST201
全量替换PUT200
部分更新PATCH200
删除资源DELETE204
批量创建POST201
复杂搜索POST200是(安全)

Pagination Decision Table

分页方案选型对照表

ApproachWhen to UseProsCons
CursorReal-time feeds, large datasetsConsistent, no skippingCannot jump to page N
OffsetSmall datasets, admin panelsSimple, jumpableSkips/duplicates on insert
KeysetTime-series, logsEfficient on large tablesRequires sortable key
方案适用场景优势劣势
游标分页实时信息流、大数据集结果一致、无数据跳过无法直接跳转到第N页
偏移量分页小数据集、管理后台简单、支持跳页数据插入时会出现跳过/重复
键集分页时序数据、日志大表查询效率高需要可排序的键

Error Response Format

错误响应格式

All endpoints must use a consistent error shape:
json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Human-readable description",
    "details": [
      { "field": "email", "message": "Invalid email format" }
    ]
  }
}
所有端点必须使用统一的错误结构:
json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "人类可读的错误描述",
    "details": [
      { "field": "email", "message": "邮箱格式无效" }
    ]
  }
}

Status Code Reference

状态码参考

CodeMeaningWhen to Use
200OKSuccessful GET, PUT, PATCH
201CreatedSuccessful POST that creates
204No ContentSuccessful DELETE
400Bad RequestValidation failure
401UnauthorizedMissing or invalid credentials
403ForbiddenValid credentials, insufficient permissions
404Not FoundResource does not exist
409ConflictDuplicate or state conflict
422Unprocessable EntityValid JSON but semantic error
429Too Many RequestsRate limit exceeded
500Internal Server ErrorUnexpected server failure
STOP after endpoint design — present each endpoint for review and approval.
状态码含义适用场景
200OKGET、PUT、PATCH请求成功
201CreatedPOST创建资源成功
204No ContentDELETE请求成功
400Bad Request参数校验失败
401Unauthorized缺失或无效凭证
403Forbidden凭证有效但权限不足
404Not Found资源不存在
409Conflict重复资源或状态冲突
422Unprocessable EntityJSON格式有效但语义错误
429Too Many Requests触发限流
500Internal Server Error意外服务端错误
端点设计完成后暂停 —— 提交所有端点供评审和确认。

Phase 3: Generate OpenAPI Spec

阶段3:生成OpenAPI规范

yaml
openapi: 3.1.0
info:
  title: [API Name]
  version: 1.0.0
  description: [API description]

servers:
  - url: http://localhost:3000/api/v1
    description: Development
  - url: https://api.example.com/v1
    description: Production

paths:
  /resource:
    get:
      summary: List resources
      parameters: [...]
      responses: [...]
    post:
      summary: Create resource
      requestBody: [...]
      responses: [...]

components:
  schemas: [...]
  securitySchemes: [...]
STOP after spec generation — validate the YAML and present for final approval.
yaml
openapi: 3.1.0
info:
  title: [API名称]
  version: 1.0.0
  description: [API描述]

servers:
  - url: http://localhost:3000/api/v1
    description: 开发环境
  - url: https://api.example.com/v1
    description: 生产环境

paths:
  /resource:
    get:
      summary: 列举资源
      parameters: [...]
      responses: [...]
    post:
      summary: 创建资源
      requestBody: [...]
      responses: [...]

components:
  schemas: [...]
  securitySchemes: [...]
规范生成后暂停 —— 验证YAML格式正确后提交最终确认。

Phase 4: Save and Transition

阶段4:保存和流程流转

After explicit approval:
  1. Save OpenAPI spec to
    docs/api/YYYY-MM-DD-<api-name>.yaml
  2. Commit with message:
    docs(api): add OpenAPI spec for <api-name>
  3. Determine next step based on user intent
获得明确确认后:
  1. 将OpenAPI规范保存到
    docs/api/YYYY-MM-DD-<api-name>.yaml
  2. 使用如下提交信息提交:
    docs(api): add OpenAPI spec for <api-name>
  3. 根据用户意图确定下一步动作

Transition Decision Table

流转决策对照表

User IntentNext SkillRationale
"Let's implement this"
planning
Create implementation plan from API spec
"Write specs for this"
spec-writing
Behavioral specs for each endpoint
"Generate client SDK"ManualUse OpenAPI codegen tools
"Just save the design"NoneAPI design is the deliverable
"Add tests"
testing-strategy
Define API test approach
用户意图后续技能原因
"我们来实现这个API吧"
planning
基于API规范制定实现方案
"为这个API编写规范"
spec-writing
为每个端点编写行为规范
"生成客户端SDK"手动操作使用OpenAPI代码生成工具
"仅保存设计即可"API设计本身就是交付物
"添加测试"
testing-strategy
定义API测试方案

Design Principles

设计原则

PrincipleRule
Consistent namingPlural nouns for collections (
/users
, not
/user
)
Proper HTTP methodsGET reads, POST creates, PUT replaces, PATCH updates, DELETE removes
Proper status codesUse the right code for the right situation (see table above)
Consistent error formatSame error shape across all endpoints
Pagination by defaultAll list endpoints paginated
Filtering and sortingQuery params for list endpoints
IdempotencyPUT and DELETE are always idempotent
HATEOASInclude links for discoverability (when appropriate)
原则规则
命名一致性集合使用复数名词命名(
/users
而不是
/user
)
正确使用HTTP方法GET用于读、POST用于创建、PUT用于替换、PATCH用于更新、DELETE用于删除
正确使用状态码根据场景使用匹配的状态码(参考上表)
错误格式统一所有端点使用相同的错误结构
默认启用分页所有列表端点都支持分页
支持过滤和排序列表端点提供对应的查询参数
幂等性保障PUT和DELETE必须是幂等的
HATEOAS合适的场景下添加链接提升可发现性

Anti-Patterns / Common Mistakes

反模式/常见错误

MistakeWhy It Is WrongWhat To Do Instead
Verb-based URLs (
/getUsers
)
Not RESTful, breaks conventionsUse nouns:
GET /users
Inconsistent plural/singularConfuses consumersAlways plural for collections
Returning 200 for errorsHides failures from clientsUse proper status codes
No pagination on list endpointsPerformance bomb on large datasetsAlways paginate
Different error formats per endpointClients can't build generic error handlingOne error shape for all
Exposing internal IDs in URLsSecurity and coupling riskUse UUIDs or slugs
No versioning strategyBreaking changes break clientsVersion from day one
Designing without knowing consumersAPI serves no one wellDiscovery phase first
错误做法问题所在正确做法
基于动词的URL(
/getUsers
)
非REST风格,违反规范使用名词:
GET /users
单复数命名不一致容易混淆调用方集合统一使用复数命名
错误返回200状态码客户端无法识别失败使用正确的错误状态码
列表端点没有分页大数据集下会引发性能问题始终启用分页
不同端点错误格式不一致客户端无法实现通用错误处理所有端点使用统一错误结构
URL中暴露内部ID存在安全和耦合风险使用UUID或slug
没有版本控制策略破坏性变更会导致客户端故障上线第一天就做版本控制
不了解调用方就开始设计API无法满足任何一方需求优先完成调研阶段

Anti-Rationalization Guards

禁止行为

  • Do NOT skip the discovery phase — understand consumers and constraints first
  • Do NOT design endpoints without defining error responses
  • Do NOT skip pagination for any list endpoint
  • Do NOT use inconsistent naming across endpoints
  • Do NOT generate the OpenAPI spec without user approval of endpoint designs
  • Do NOT mix API paradigms (REST + GraphQL) without explicit justification
  • 严禁跳过调研阶段 —— 必须先明确调用方需求和约束条件
  • 严禁不定义错误响应就设计端点
  • 严禁任何列表端点跳过分页设计
  • 严禁端点之间使用不一致的命名规则
  • 严禁未获得用户确认端点设计就生成OpenAPI规范
  • 严禁没有明确理由就混合使用多种API范式(REST + GraphQL)

Integration Points

关联技能

SkillRelationship
spec-writing
Downstream: API design informs behavioral specifications
planning
Downstream: API endpoints become implementation tasks
tech-docs-generator
Downstream: OpenAPI spec feeds API reference docs
testing-strategy
Downstream: API design informs integration test strategy
security-review
Downstream: auth/authz model reviewed for vulnerabilities
database-schema-design
Upstream: data model informs resource design
prd-generation
Upstream: PRD requirements drive API resource identification
技能关联关系
spec-writing
下游:API设计为行为规范提供输入
planning
下游:API端点会转化为开发任务
tech-docs-generator
下游:OpenAPI规范可用于生成API参考文档
testing-strategy
下游:API设计为集成测试方案提供输入
security-review
下游:可对鉴权/授权模型做安全漏洞评审
database-schema-design
上游:数据模型为资源设计提供输入
prd-generation
上游:PRD需求驱动API资源识别

Verification Gate

校验关口

Before claiming the API design is complete:
  1. VERIFY all endpoints have request/response schemas
  2. VERIFY all error responses are documented with consistent format
  3. VERIFY authentication is specified for each endpoint
  4. VERIFY pagination is defined for all list endpoints
  5. VERIFY the OpenAPI spec is valid YAML
  6. VERIFY user has approved each endpoint individually
在确认API设计完成前:
  1. 确认所有端点都定义了请求/响应schema
  2. 确认所有错误响应都已文档化且格式统一
  3. 确认每个端点都指定了身份认证规则
  4. 确认所有列表端点都定义了分页方案
  5. 确认OpenAPI规范是有效的YAML格式
  6. 确认用户已单独确认每个端点的设计

Skill Type

技能类型

Flexible — Adapt API paradigm, pagination style, and auth model to project needs while preserving the discovery-first approach, consistent error handling, and consumer-centric design principles.
灵活适配型 —— 可根据项目需求调整API范式、分页方式和鉴权模型,同时保留调研优先的流程、一致的错误处理机制和以调用方为中心的设计原则。