api-design
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI 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
资源相关问题
| # | Question | What It Determines |
|---|---|---|
| 1 | What entities/resources does this API manage? | Resource naming |
| 2 | What are the relationships between them? | Nested routes, includes |
| 3 | What operations are needed for each? (CRUD, search, batch) | HTTP methods, endpoints |
| # | 问题 | 作用 |
|---|---|---|
| 1 | 该API管理哪些实体/资源? | 资源命名 |
| 2 | 资源之间存在什么关系? | 嵌套路由、关联字段 |
| 3 | 每个资源需要支持哪些操作?(CRUD、搜索、批量操作) | HTTP方法、端点定义 |
Consumer Questions
调用方相关问题
| # | Question | What It Determines |
|---|---|---|
| 4 | Who will consume this API? (frontend, mobile, third-party, internal) | Response shape, auth model |
| 5 | What authentication/authorization is needed? | Security scheme |
| 6 | What rate limits or quotas apply? | Rate limiting headers |
| # | 问题 | 作用 |
|---|---|---|
| 4 | 哪些角色会调用该API?(前端、移动端、第三方、内部服务) | 响应结构、鉴权模型 |
| 5 | 需要什么样的身份认证/授权机制? | 安全方案 |
| 6 | 适用什么限流规则或配额? | 限流响应头 |
Constraint Questions
约束条件相关问题
| # | Question | What It Determines |
|---|---|---|
| 7 | REST, GraphQL, or tRPC? | API paradigm |
| 8 | Versioning strategy? (URL path, header, query param) | URL structure |
| 9 | Pagination approach? (cursor, offset, keyset) | List response shape |
| 10 | Existing API conventions in the codebase? | Consistency constraints |
| # | 问题 | 作用 |
|---|---|---|
| 7 | 选用REST、GraphQL还是tRPC? | API开发范式 |
| 8 | 版本控制策略是什么?(URL路径、请求头、查询参数) | URL结构 |
| 9 | 分页方案是什么?(游标、偏移量、键集) | 列表响应结构 |
| 10 | 代码库中现有API规范是什么? | 一致性约束 |
API Paradigm Decision Table
API范式选型对照表
| Factor | Choose REST | Choose GraphQL | Choose tRPC |
|---|---|---|---|
| Consumers | Multiple, diverse | Frontend-heavy, flexible queries | TypeScript monorepo |
| Caching needs | Strong (HTTP caching) | Moderate (client-side) | Low (internal only) |
| Data shape | Predictable, resource-oriented | Nested, variable-shape | Type-safe RPC |
| Team familiarity | Universal | Requires schema knowledge | Requires TypeScript |
| Real-time needs | WebSocket addon | Subscriptions built-in | Subscription 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:
| Status | Code | Description |
|---|---|---|
| 400 | VALIDATION_ERROR | Invalid request body |
| 401 | UNAUTHORIZED | Missing or invalid token |
| 404 | NOT_FOUND | Resource doesn't exist |
| 409 | CONFLICT | Resource 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 }
}错误响应:
| 状态码 | 错误码 | 说明 |
|---|---|---|
| 400 | VALIDATION_ERROR | 请求体校验失败 |
| 401 | UNAUTHORIZED | 缺失或无效token |
| 404 | NOT_FOUND | 资源不存在 |
| 409 | CONFLICT | 资源已存在 |
授权规则: [可访问该端点的角色说明]
undefinedHTTP Method Decision Table
HTTP方法选型对照表
| Operation | Method | Status (success) | Idempotent |
|---|---|---|---|
| List resources | GET | 200 | Yes |
| Get single resource | GET | 200 | Yes |
| Create resource | POST | 201 | No |
| Full replace | PUT | 200 | Yes |
| Partial update | PATCH | 200 | No |
| Delete resource | DELETE | 204 | Yes |
| Bulk create | POST | 201 | No |
| Search (complex) | POST | 200 | Yes (safe) |
| 操作 | 方法 | 成功状态码 | 幂等性 |
|---|---|---|---|
| 列举资源 | GET | 200 | 是 |
| 获取单个资源 | GET | 200 | 是 |
| 创建资源 | POST | 201 | 否 |
| 全量替换 | PUT | 200 | 是 |
| 部分更新 | PATCH | 200 | 否 |
| 删除资源 | DELETE | 204 | 是 |
| 批量创建 | POST | 201 | 否 |
| 复杂搜索 | POST | 200 | 是(安全) |
Pagination Decision Table
分页方案选型对照表
| Approach | When to Use | Pros | Cons |
|---|---|---|---|
| Cursor | Real-time feeds, large datasets | Consistent, no skipping | Cannot jump to page N |
| Offset | Small datasets, admin panels | Simple, jumpable | Skips/duplicates on insert |
| Keyset | Time-series, logs | Efficient on large tables | Requires 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
状态码参考
| Code | Meaning | When to Use |
|---|---|---|
| 200 | OK | Successful GET, PUT, PATCH |
| 201 | Created | Successful POST that creates |
| 204 | No Content | Successful DELETE |
| 400 | Bad Request | Validation failure |
| 401 | Unauthorized | Missing or invalid credentials |
| 403 | Forbidden | Valid credentials, insufficient permissions |
| 404 | Not Found | Resource does not exist |
| 409 | Conflict | Duplicate or state conflict |
| 422 | Unprocessable Entity | Valid JSON but semantic error |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Unexpected server failure |
STOP after endpoint design — present each endpoint for review and approval.
| 状态码 | 含义 | 适用场景 |
|---|---|---|
| 200 | OK | GET、PUT、PATCH请求成功 |
| 201 | Created | POST创建资源成功 |
| 204 | No Content | DELETE请求成功 |
| 400 | Bad Request | 参数校验失败 |
| 401 | Unauthorized | 缺失或无效凭证 |
| 403 | Forbidden | 凭证有效但权限不足 |
| 404 | Not Found | 资源不存在 |
| 409 | Conflict | 重复资源或状态冲突 |
| 422 | Unprocessable Entity | JSON格式有效但语义错误 |
| 429 | Too Many Requests | 触发限流 |
| 500 | Internal 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:
- Save OpenAPI spec to
docs/api/YYYY-MM-DD-<api-name>.yaml - Commit with message:
docs(api): add OpenAPI spec for <api-name> - Determine next step based on user intent
获得明确确认后:
- 将OpenAPI规范保存到
docs/api/YYYY-MM-DD-<api-name>.yaml - 使用如下提交信息提交:
docs(api): add OpenAPI spec for <api-name> - 根据用户意图确定下一步动作
Transition Decision Table
流转决策对照表
| User Intent | Next Skill | Rationale |
|---|---|---|
| "Let's implement this" | | Create implementation plan from API spec |
| "Write specs for this" | | Behavioral specs for each endpoint |
| "Generate client SDK" | Manual | Use OpenAPI codegen tools |
| "Just save the design" | None | API design is the deliverable |
| "Add tests" | | Define API test approach |
| 用户意图 | 后续技能 | 原因 |
|---|---|---|
| "我们来实现这个API吧" | | 基于API规范制定实现方案 |
| "为这个API编写规范" | | 为每个端点编写行为规范 |
| "生成客户端SDK" | 手动操作 | 使用OpenAPI代码生成工具 |
| "仅保存设计即可" | 无 | API设计本身就是交付物 |
| "添加测试" | | 定义API测试方案 |
Design Principles
设计原则
| Principle | Rule |
|---|---|
| Consistent naming | Plural nouns for collections ( |
| Proper HTTP methods | GET reads, POST creates, PUT replaces, PATCH updates, DELETE removes |
| Proper status codes | Use the right code for the right situation (see table above) |
| Consistent error format | Same error shape across all endpoints |
| Pagination by default | All list endpoints paginated |
| Filtering and sorting | Query params for list endpoints |
| Idempotency | PUT and DELETE are always idempotent |
| HATEOAS | Include links for discoverability (when appropriate) |
| 原则 | 规则 |
|---|---|
| 命名一致性 | 集合使用复数名词命名( |
| 正确使用HTTP方法 | GET用于读、POST用于创建、PUT用于替换、PATCH用于更新、DELETE用于删除 |
| 正确使用状态码 | 根据场景使用匹配的状态码(参考上表) |
| 错误格式统一 | 所有端点使用相同的错误结构 |
| 默认启用分页 | 所有列表端点都支持分页 |
| 支持过滤和排序 | 列表端点提供对应的查询参数 |
| 幂等性保障 | PUT和DELETE必须是幂等的 |
| HATEOAS | 合适的场景下添加链接提升可发现性 |
Anti-Patterns / Common Mistakes
反模式/常见错误
| Mistake | Why It Is Wrong | What To Do Instead |
|---|---|---|
Verb-based URLs ( | Not RESTful, breaks conventions | Use nouns: |
| Inconsistent plural/singular | Confuses consumers | Always plural for collections |
| Returning 200 for errors | Hides failures from clients | Use proper status codes |
| No pagination on list endpoints | Performance bomb on large datasets | Always paginate |
| Different error formats per endpoint | Clients can't build generic error handling | One error shape for all |
| Exposing internal IDs in URLs | Security and coupling risk | Use UUIDs or slugs |
| No versioning strategy | Breaking changes break clients | Version from day one |
| Designing without knowing consumers | API serves no one well | Discovery phase first |
| 错误做法 | 问题所在 | 正确做法 |
|---|---|---|
基于动词的URL( | 非REST风格,违反规范 | 使用名词: |
| 单复数命名不一致 | 容易混淆调用方 | 集合统一使用复数命名 |
| 错误返回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
关联技能
| Skill | Relationship |
|---|---|
| Downstream: API design informs behavioral specifications |
| Downstream: API endpoints become implementation tasks |
| Downstream: OpenAPI spec feeds API reference docs |
| Downstream: API design informs integration test strategy |
| Downstream: auth/authz model reviewed for vulnerabilities |
| Upstream: data model informs resource design |
| Upstream: PRD requirements drive API resource identification |
| 技能 | 关联关系 |
|---|---|
| 下游:API设计为行为规范提供输入 |
| 下游:API端点会转化为开发任务 |
| 下游:OpenAPI规范可用于生成API参考文档 |
| 下游:API设计为集成测试方案提供输入 |
| 下游:可对鉴权/授权模型做安全漏洞评审 |
| 上游:数据模型为资源设计提供输入 |
| 上游:PRD需求驱动API资源识别 |
Verification Gate
校验关口
Before claiming the API design is complete:
- VERIFY all endpoints have request/response schemas
- VERIFY all error responses are documented with consistent format
- VERIFY authentication is specified for each endpoint
- VERIFY pagination is defined for all list endpoints
- VERIFY the OpenAPI spec is valid YAML
- VERIFY user has approved each endpoint individually
在确认API设计完成前:
- 确认所有端点都定义了请求/响应schema
- 确认所有错误响应都已文档化且格式统一
- 确认每个端点都指定了身份认证规则
- 确认所有列表端点都定义了分页方案
- 确认OpenAPI规范是有效的YAML格式
- 确认用户已单独确认每个端点的设计
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范式、分页方式和鉴权模型,同时保留调研优先的流程、一致的错误处理机制和以调用方为中心的设计原则。