dev-api-design
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Development & Design — Quick Reference
API开发与设计——快速参考
Use this skill to design, implement, and document production-grade APIs (REST, GraphQL, gRPC, and tRPC). Apply it for contract design (OpenAPI), versioning/deprecation, authentication/authorization, rate limiting, pagination, error models, and developer documentation.
Modern best practices (Jan 2026): HTTP semantics and cacheability (RFC 9110), Problem Details error model (RFC 9457), OpenAPI 3.1+, contract-first + breaking-change detection, strong AuthN/Z boundaries, explicit versioning/deprecation, and operable-by-default APIs (idempotency, rate limits, observability, trace context).
使用本技能来设计、实现和记录生产级API(REST、GraphQL、gRPC和tRPC)。可应用于契约设计(OpenAPI)、版本控制/弃用、身份验证/授权、速率限制、分页、错误模型以及开发者文档等场景。
2026年1月现代最佳实践:HTTP语义与可缓存性(RFC 9110)、Problem Details错误模型(RFC 9457)、OpenAPI 3.1+、契约优先+破坏性变更检测、清晰的AuthN/AuthZ边界、明确的版本控制/弃用策略,以及默认可运维的API(幂等性、速率限制、可观测性、追踪上下文)。
Default Execution Checklist
默认执行检查清单
- Choose an API style based on constraints (public vs internal, performance, client query flexibility).
- Define the contract first (OpenAPI or GraphQL schema; protobuf for gRPC).
- Define the error model (RFC 9457 + stable error codes + trace IDs).
- Define AuthN/AuthZ boundaries (scopes/roles/tenancy) and threat model.
- Define pagination/filter/sort for all list endpoints.
- Define rate limits/quotas, idempotency strategy (esp. POST), and retries/backoff guidance.
- Define observability (W3C Trace Context, request IDs, metrics, logs) and SLOs.
- Add contract tests + breaking-change checks in CI.
- Publish docs with examples + migration/deprecation policy.
- 根据约束条件选择API风格(公开vs内部、性能要求、客户端查询灵活性)。
- 优先定义契约(OpenAPI或GraphQL schema;gRPC使用protobuf)。
- 定义错误模型(RFC 9457 + 稳定错误码 + 追踪ID)。
- 定义AuthN/AuthZ边界(权限范围/角色/租户)并进行威胁建模。
- 为所有列表端点定义分页/过滤/排序规则。
- 定义速率限制/配额、幂等性策略(尤其是POST请求),以及重试/退避指导。
- 定义可观测性(W3C Trace Context、请求ID、指标、日志)和SLO。
- 在CI中添加契约测试+破坏性变更检查。
- 发布包含示例+迁移/弃用策略的文档。
Quick Reference
快速参考
| Task | Pattern/Tool | Key Elements | When to Use |
|---|---|---|---|
| Design REST API | RESTful Design | Nouns (not verbs), HTTP methods, proper status codes | Resource-based APIs, CRUD operations |
| Version API | URL Versioning | | Breaking changes, client migration |
| Paginate results | Cursor-Based | | Real-time data, large collections |
| Handle errors | RFC 9457 Problem Details | | Consistent error responses |
| Authenticate | JWT Bearer | | Stateless auth, microservices |
| Rate limit | Token Bucket | | Prevent abuse, fair usage |
| Document API | OpenAPI 3.1 | Swagger UI, Redoc, code samples | Interactive docs, client SDKs |
| Flexible queries | GraphQL | Schema-first, resolvers, DataLoader | Client-driven data fetching |
| High-performance | gRPC + Protobuf | Binary protocol, streaming | Internal microservices |
| TypeScript-first | tRPC | End-to-end type safety, no codegen | Monorepos, internal tools |
| AI agent APIs | REST + MCP | Agent experience, machine-readable | LLM/agent consumption |
| 任务 | 模式/工具 | 核心要素 | 使用场景 |
|---|---|---|---|
| 设计REST API | RESTful设计 | 名词(而非动词)、HTTP方法、正确的状态码 | 基于资源的API、CRUD操作 |
| API版本控制 | URL版本控制 | | 破坏性变更、客户端迁移 |
| 结果分页 | 基于游标 | | 实时数据、大型数据集 |
| 错误处理 | RFC 9457 Problem Details | | 一致的错误响应 |
| 身份验证 | JWT Bearer | | 无状态认证、微服务 |
| 速率限制 | 令牌桶算法 | | 防止滥用、公平使用 |
| API文档 | OpenAPI 3.1 | Swagger UI、Redoc、代码示例 | 交互式文档、客户端SDK |
| 灵活查询 | GraphQL | schema优先、解析器、DataLoader | 客户端驱动的数据获取 |
| 高性能场景 | gRPC + Protobuf | 二进制协议、流式传输 | 内部微服务 |
| TypeScript优先 | tRPC | 端到端类型安全、无需代码生成 | 单仓库、内部工具 |
| AI Agent API | REST + MCP | Agent适配、机器可读格式 | LLM/Agent调用 |
Decision Tree: Choosing API Style
决策树:选择API风格
text
User needs: [API Type]
├─ Public API for third parties?
│ └─ REST with OpenAPI docs (broad compatibility)
│
├─ Internal microservices?
│ ├─ High throughput required? → **gRPC** (binary, fast)
│ └─ Simple CRUD? → **REST** (easy to debug)
│
├─ TypeScript monorepo (frontend + backend)?
│ └─ **tRPC** (end-to-end type safety, no codegen)
│
├─ Client needs flexible queries?
│ ├─ Real-time updates? → **GraphQL Subscriptions** or **WebSockets**
│ └─ Complex data fetching? → **GraphQL** (avoid over-fetching)
│
├─ Mobile/web clients?
│ ├─ Many entity types? → **GraphQL** (single endpoint)
│ └─ Simple resources? → **REST** (cacheable)
│
├─ AI agents consuming API?
│ └─ REST + **MCP** wrapper (agent experience)
│
└─ Streaming or bidirectional?
└─ **gRPC** (HTTP/2 streaming) or **WebSockets**text
用户需求: [API类型]
├─ 面向第三方的公开API?
│ └─ 搭配OpenAPI文档的REST(兼容性广)
│
├─ 内部微服务?
│ ├─ 需要高吞吐量?→ **gRPC**(二进制、高速)
│ └─ 简单CRUD?→ **REST**(易于调试)
│
├─ TypeScript单仓库(前端+后端)?
│ └─ **tRPC**(端到端类型安全、无需代码生成)
│
├─ 客户端需要灵活查询?
│ ├─ 实时更新?→ **GraphQL Subscriptions** 或 **WebSockets**
│ └─ 复杂数据获取?→ **GraphQL**(避免过度获取)
│
├─ 移动/网页客户端?
│ ├─ 多种实体类型?→ **GraphQL**(单一端点)
│ └─ 简单资源?→ **REST**(可缓存)
│
├─ AI Agent调用API?
│ └─ REST + **MCP**包装层(Agent适配)
│
└─ 流式或双向通信?
└─ **gRPC**(HTTP/2流式)或 **WebSockets**Navigation: Core API Patterns
导航:核心API模式
RESTful API Design
RESTful API设计
Resource: references/restful-design-patterns.md
- Resource-based URLs with proper HTTP methods (GET, POST, PUT, PATCH, DELETE)
- HTTP status code semantics (200, 201, 404, 422, 500)
- Idempotency guarantees (GET, PUT, DELETE)
- Stateless design principles
- URL structure best practices (collection vs resource endpoints)
- Nested resources and action endpoints
资源: references/restful-design-patterns.md
- 基于资源的URL搭配正确的HTTP方法(GET、POST、PUT、PATCH、DELETE)
- HTTP状态码语义(200、201、404、422、500)
- 幂等性保证(GET、PUT、DELETE)
- 无状态设计原则
- URL结构最佳实践(集合 vs 资源端点)
- 嵌套资源与动作端点
Pagination, Filtering & Sorting
分页、过滤与排序
Resource: references/pagination-filtering.md
- Offset-based pagination (simple, static datasets)
- Cursor-based pagination (real-time feeds, recommended)
- Page-based pagination (UI with page numbers)
- Query parameter filtering with operators (,
_gt,_contains)_in - Multi-field sorting with direction ()
-created_at - Performance optimization with indexes
资源: references/pagination-filtering.md
- 基于偏移量的分页(简单、静态数据集)
- 基于游标的分页(实时信息流、推荐使用)
- 基于页码的分页(带页码的UI)
- 带操作符的查询参数过滤(、
_gt、_contains)_in - 带方向的多字段排序()
-created_at - 基于索引的性能优化
Error Handling
错误处理
Resource: references/error-handling-patterns.md
- RFC 9457 Problem Details standard
- HTTP status code reference (4xx client errors, 5xx server errors)
- Field-level validation errors
- Trace IDs for debugging
- Consistent error format across endpoints
- Security-safe error messages (no stack traces in production)
资源: references/error-handling-patterns.md
- RFC 9457 Problem Details标准
- HTTP状态码参考(4xx客户端错误、5xx服务器错误)
- 字段级验证错误
- 用于调试的追踪ID
- 跨端点的一致错误格式
- 生产环境安全的错误信息(不返回堆栈跟踪)
Authentication & Authorization
身份验证与授权
Resource: references/authentication-patterns.md
- JWT (JSON Web Tokens) with refresh token rotation
- OAuth2 Authorization Code Flow for third-party auth
- API Key authentication for server-to-server
- RBAC (Role-Based Access Control)
- ABAC (Attribute-Based Access Control)
- Resource-based authorization (user-owned resources)
资源: references/authentication-patterns.md
- 带刷新令牌轮转的JWT(JSON Web Tokens)
- 用于第三方认证的OAuth2授权码流程
- 用于服务器间通信的API Key认证
- RBAC(基于角色的访问控制)
- ABAC(基于属性的访问控制)
- 基于资源的授权(用户自有资源)
Rate Limiting & Throttling
速率限制与限流
Resource: references/rate-limiting-patterns.md
- Token Bucket algorithm (recommended, allows bursts)
- Fixed Window vs Sliding Window
- Rate limit headers ()
X-RateLimit-* - Tiered rate limits (free, paid, enterprise)
- Redis-based distributed rate limiting
- Per-user, per-endpoint, and per-API-key strategies
资源: references/rate-limiting-patterns.md
- 令牌桶算法(推荐、支持突发流量)
- 固定窗口 vs 滑动窗口
- 速率限制响应头()
X-RateLimit-* - 分层速率限制(免费、付费、企业版)
- 基于Redis的分布式速率限制
- 按用户、按端点、按API Key的策略
Navigation: Extended Resources
导航:扩展资源
API Design & Best Practices
API设计与最佳实践
- api-design-best-practices.md - Comprehensive API design principles
- versioning-strategies.md - URL, header, and query parameter versioning
- api-security-checklist.md - OWASP API Security Top 10
- api-design-best-practices.md - 全面的API设计原则
- versioning-strategies.md - URL、响应头、查询参数版本控制
- api-security-checklist.md - OWASP API安全Top 10
GraphQL & gRPC
GraphQL & gRPC
- graphql-patterns.md - Schema design, resolvers, N+1 queries, DataLoader
- gRPC patterns - See software-backend for Protocol Buffers and service definitions
- graphql-patterns.md - Schema设计、解析器、N+1查询问题、DataLoader
- gRPC模式 - 查看software-backend获取Protocol Buffers和服务定义相关内容
tRPC (TypeScript-First)
tRPC(TypeScript优先)
- trpc-patterns.md - End-to-end type safety, procedures, React Query integration
- When to use tRPC vs GraphQL vs REST
- Auth middleware patterns
- Server-side rendering with Next.js
- trpc-patterns.md - 端到端类型安全、流程、React Query集成
- tRPC vs GraphQL vs REST的适用场景
- 认证中间件模式
- 搭配Next.js的服务端渲染
OpenAPI & Documentation
OpenAPI与文档
- openapi-guide.md - OpenAPI 3.1 specifications, Swagger UI, Redoc
- Templates: assets/openapi-template.yaml - Complete OpenAPI spec example
- openapi-guide.md - OpenAPI 3.1规范、Swagger UI、Redoc
- 模板: assets/openapi-template.yaml - 完整的OpenAPI规范示例
Optional: AI/Automation (LLM/Agent APIs)
可选:AI/自动化(LLM/Agent API)
- llm-agent-api-contracts.md - Streaming, long-running jobs, safety guardrails, observability
- llm-agent-api-contracts.md - 流式传输、长时任务、安全防护、可观测性
Navigation: Templates
导航:模板
Production-ready, copy-paste API implementations with authentication, database, validation, and docs.
可直接复制使用的生产级API实现模板,包含认证、数据库、验证和文档功能。
Framework-Specific Templates
框架特定模板
-
FastAPI (Python): assets/fastapi/fastapi-complete-api.md
- Async/await, Pydantic v2, JWT auth, SQLAlchemy 2.0, pagination, OpenAPI docs
-
Express.js (Node/TypeScript): assets/express-nodejs/express-complete-api.md
- TypeScript, Zod validation, Prisma ORM, JWT refresh tokens, rate limiting
-
Django REST Framework: assets/django-rest/django-rest-complete-api.md
- ViewSets, serializers, Simple JWT, permissions, DRF filtering/pagination
-
Spring Boot (Java): assets/spring-boot/spring-boot-complete-api.md
- Spring Security JWT, Spring Data JPA, Bean Validation, Springdoc OpenAPI
-
FastAPI(Python):assets/fastapi/fastapi-complete-api.md
- 异步/等待、Pydantic v2、JWT认证、SQLAlchemy 2.0、分页、OpenAPI文档
-
Express.js(Node/TypeScript):assets/express-nodejs/express-complete-api.md
- TypeScript、Zod验证、Prisma ORM、JWT刷新令牌、速率限制
-
Django REST Framework:assets/django-rest/django-rest-complete-api.md
- ViewSets、序列化器、Simple JWT、权限控制、DRF过滤/分页
-
Spring Boot(Java):assets/spring-boot/spring-boot-complete-api.md
- Spring Security JWT、Spring Data JPA、Bean Validation、Springdoc OpenAPI
Cross-Platform Patterns
跨平台模式
- api-patterns-universal.md - Universal patterns for all frameworks
- Authentication strategies, pagination, caching, versioning, validation
- template-api-governance.md - API governance, deprecation, multi-tenancy
- Deprecation policy (90-day timeline), backward compatibility rules, error model templates
- template-api-design-review-checklist.md - Production API review checklist (security, reliability, operability)
- template-api-error-model.md - RFC 9457 Problem Details + stable error code registry
- api-patterns-universal.md - 适用于所有框架的通用模式
- 认证策略、分页、缓存、版本控制、验证
- template-api-governance.md - API治理、弃用、多租户
- 弃用策略(90天过渡期)、向后兼容规则、错误模型模板
- template-api-design-review-checklist.md - 生产级API评审清单(安全、可靠性、可运维性)
- template-api-error-model.md - RFC 9457 Problem Details + 稳定错误码注册表
Do / Avoid
应做/避免
GOOD: Do
推荐:应做
- Version APIs from day one
- Document deprecation policy before first deprecation
- Treat breaking changes as a major version (and keep minor changes backward compatible)
- Include trace IDs in all error responses
- Return appropriate HTTP status codes
- Implement rate limiting with clear headers
- Use RFC 9457 Problem Details for errors
- 从项目初期就为API添加版本控制
- 在首次弃用前明确文档化弃用策略
- 将破坏性变更视为大版本更新(小版本变更需保持向后兼容)
- 在所有错误响应中包含追踪ID
- 返回合适的HTTP状态码
- 实现带清晰响应头的速率限制
- 使用RFC 9457 Problem Details格式返回错误
BAD: Avoid
不推荐:避免
- Removing fields without deprecation period
- Changing field types in existing versions
- Using verbs in resource names (nouns only)
- Returning 500 for client errors
- Breaking changes without major version bump
- Mixing tenant data without explicit isolation
- Action endpoints everywhere (/doSomething)
- 未设置弃用周期就删除字段
- 在现有版本中修改字段类型
- 资源名称使用动词(仅使用名词)
- 客户端错误返回500状态码
- 破坏性变更未升级大版本
- 未明确隔离就混合租户数据
- 大量使用动作端点(如/doSomething)
Anti-Patterns
反模式
| Anti-Pattern | Problem | Fix |
|---|---|---|
| Instant deprecation | Breaks clients | 90-day minimum sunset period |
| Action endpoints | Inconsistent API | Use resources + HTTP verbs |
| Version in body | Hard to route, debug | Version in URL or header |
| Generic errors | Poor DX | Specific error codes + messages |
| No rate limit headers | Clients can't back off | Include X-RateLimit-* |
| Tenant ID in URL only | Forgery risk | Validate against auth token |
| Leaky abstractions | Tight coupling | Design stable contracts |
| 反模式 | 问题 | 修复方案 |
|---|---|---|
| 立即弃用 | 导致客户端崩溃 | 至少90天的过渡期 |
| 动作端点 | API风格不一致 | 使用资源+HTTP动词 |
| 版本放在请求体 | 路由、调试困难 | 版本放在URL或响应头 |
| 通用错误信息 | 开发者体验差 | 具体错误码+详细信息 |
| 无速率限制响应头 | 客户端无法自动退避 | 添加X-RateLimit-*响应头 |
| 仅在URL中传递租户ID | 存在伪造风险 | 结合认证令牌验证租户ID |
| 抽象泄露 | 紧耦合 | 设计稳定的契约 |
Optional: AI/Automation
可选:AI/自动化
Note: AI tools assist but contracts need human review.
- OpenAPI linting — Spectral, Redocly in CI/CD
- Breaking change detection — oasdiff automated checks
- SDK generation — From OpenAPI spec on changes
- Contract testing — Pact, Dredd automation
注意:AI工具仅作辅助,契约仍需人工审核。
- OpenAPI校验 — 在CI/CD中使用Spectral、Redocly
- 破坏性变更检测 — 使用oasdiff自动检查
- SDK生成 — 基于OpenAPI规范变更自动生成
- 契约测试 — Pact、Dredd自动化测试
Bounded Claims
边界限制
- AI-generated OpenAPI specs require human review
- Automated deprecation detection needs manual confirmation
- SDK generation requires type verification
- AI生成的OpenAPI规范需要人工审核
- 自动化弃用检测需要人工确认
- SDK生成需要类型验证
External Resources
外部资源
See data/sources.json for:
- Official REST, GraphQL, gRPC documentation
- OpenAPI/Swagger tools and validators
- API design style guides (Google, Microsoft, Stripe)
- Security standards (OWASP API Security Top 10)
- Testing tools (Postman, Insomnia, Paw)
查看data/sources.json获取:
- REST、GraphQL、gRPC官方文档
- OpenAPI/Swagger工具与验证器
- API设计风格指南(谷歌、微软、Stripe)
- 安全标准(OWASP API安全Top 10)
- 测试工具(Postman、Insomnia、Paw)
Related Skills
相关技能
This skill works best when combined with other specialized skills:
本技能与以下专业技能搭配使用效果最佳:
Backend Development
后端开发
- software-backend - Production backend patterns (Node.js, Python, Java frameworks)
- Use when implementing API server infrastructure
- Covers database integration, middleware, error handling
- software-backend - 生产级后端模式(Node.js、Python、Java框架)
- 实现API服务器基础设施时使用
- 涵盖数据库集成、中间件、错误处理
Security & Authentication
安全与认证
- software-security-appsec - Application security patterns
- Critical for securing API endpoints
- Covers OWASP vulnerabilities, authentication flows, input validation
- software-security-appsec - 应用安全模式
- 对API端点安全至关重要
- 涵盖OWASP漏洞、认证流程、输入验证
Database & Data Layer
数据库与数据层
- data-sql-optimization - SQL optimization and database patterns
- Essential for API performance (query optimization, indexing)
- Use when APIs interact with relational databases
- data-sql-optimization - SQL优化与数据库模式
- 对API性能至关重要(查询优化、索引)
- API与关系型数据库交互时使用
Testing & Quality
测试与质量
- qa-testing-strategy - Test strategy and automation
- Contract testing for API specifications
- Integration testing for API endpoints
- qa-testing-strategy - 测试策略与自动化
- API规范的契约测试
- API端点的集成测试
DevOps & Deployment
DevOps与部署
- ops-devops-platform - Platform engineering and deployment
- API gateway configuration
- CI/CD pipelines for API deployments
- ops-devops-platform - 平台工程与部署
- API网关配置
- API部署的CI/CD流水线
Documentation
文档
- docs-codebase - Technical documentation standards
- API reference documentation structure
- Complements OpenAPI auto-generated docs
- docs-codebase - 技术文档标准
- API参考文档结构
- 补充OpenAPI自动生成的文档
Architecture
架构
- software-architecture-design - System design patterns
- Microservices architecture with APIs
- API gateway patterns, service mesh integration
- software-architecture-design - 系统设计模式
- 搭配API的微服务架构
- API网关模式、服务网格集成
Performance & Observability
性能与可观测性
- qa-observability - Performance optimization and monitoring
- API latency monitoring, distributed tracing
- Performance budgets for API endpoints
- qa-observability - 性能优化与监控
- API延迟监控、分布式追踪
- API端点的性能预算
Usage Notes
使用说明
For the agent:
- Apply RESTful principles by default unless user requests GraphQL/gRPC
- Always include pagination for list endpoints
- Use RFC 9457 format for error responses
- Include authentication in all templates (JWT or API keys)
- Reference framework-specific templates for complete implementations
- Link to relevant resources for deep-dive guidance
Success Criteria: APIs are discoverable, consistent, well-documented, secure, and follow HTTP/GraphQL semantics correctly.
面向Agent:
- 默认应用RESTful原则,除非用户明确要求GraphQL/gRPC
- 所有列表端点必须实现分页
- 使用RFC 9457格式返回错误响应
- 所有模板包含认证功能(JWT或API Key)
- 参考框架特定模板完成完整实现
- 链接到相关资源以提供深度指导
成功标准:API具备可发现性、一致性、完善的文档、安全性,并正确遵循HTTP/GraphQL语义。
Time-Sensitive Recommendations
时效性建议
If a user asks for "best" tools/frameworks, "latest" standards, or whether something is still relevant in 2026, do a quick web search using whatever browsing/search tool is available in the current environment. If web access is unavailable, answer from stable principles, state assumptions (traffic, latency, team skills, ecosystem), and avoid overstating currency.
如果用户询问“最佳”工具/框架、“最新”标准,或某技术在2026年是否仍适用,请使用当前环境中的浏览/搜索工具进行快速查询。若无法访问网络,请基于稳定原则作答,说明假设条件(流量、延迟、团队技能、生态),避免过度强调时效性。