api-design
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Design
API设计
Comprehensive API design patterns covering REST/GraphQL framework design, versioning strategies, and RFC 9457 error handling. Each category has individual rule files in loaded on-demand.
rules/涵盖REST/GraphQL框架设计、版本控制策略以及RFC 9457错误处理的全面API设计模式。每个类别在目录下都有独立的规则文件,可按需加载。
rules/Quick Reference
快速参考
| Category | Rules | Impact | When to Use |
|---|---|---|---|
| API Framework | 3 | HIGH | REST conventions, resource modeling, OpenAPI specifications |
| Versioning | 3 | HIGH | URL path versioning, header versioning, deprecation/sunset policies |
| Error Handling | 3 | HIGH | RFC 9457 Problem Details, validation errors, error type registries |
| GraphQL | 2 | HIGH | Strawberry code-first, DataLoader, permissions, subscriptions |
| gRPC | 2 | HIGH | Protobuf services, streaming, interceptors, retry |
| Streaming | 2 | HIGH | SSE endpoints, WebSocket bidirectional, async generators |
Total: 15 rules across 6 categories
API Framework
API框架
REST and GraphQL API design conventions for consistent, developer-friendly APIs.
| Rule | File | Key Pattern |
|---|---|---|
| REST Conventions | | Plural nouns, HTTP methods, status codes, pagination |
| Resource Modeling | | Hierarchical URLs, filtering, sorting, field selection |
| OpenAPI | | OpenAPI 3.1 specs, documentation, schema definitions |
用于构建一致、开发者友好型API的REST和GraphQL设计规范。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| REST规范 | | 复数名词、HTTP方法、状态码、分页 |
| 资源建模 | | 层级URL、过滤、排序、字段选择 |
| OpenAPI | | OpenAPI 3.1规范、文档、Schema定义 |
Versioning
版本控制
Strategies for API evolution without breaking clients.
| Rule | File | Key Pattern |
|---|---|---|
| URL Path | | |
| Header | | |
| Deprecation | | Sunset headers, lifecycle management, breaking change policy |
在不破坏客户端兼容性的前提下实现API演进的策略。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| URL路径版本 | | |
| 请求头版本 | | |
| 废弃策略 | | Sunset请求头、生命周期管理、破坏性变更政策 |
Error Handling
错误处理
RFC 9457 Problem Details for machine-readable, standardized error responses.
| Rule | File | Key Pattern |
|---|---|---|
| Problem Details | | RFC 9457 schema, |
| Validation | | Field-level errors, Pydantic integration, 422 responses |
| Error Catalog | | Problem type registry, error type URIs, client handling |
基于RFC 9457 Problem Details的机器可读标准化错误响应方案。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| Problem Details | | RFC 9457 Schema、 |
| 校验错误 | | 字段级错误、Pydantic集成、422响应 |
| 错误目录 | | Problem类型注册表、错误类型URI、客户端处理 |
GraphQL
GraphQL
Strawberry GraphQL code-first schema with type-safe resolvers and FastAPI integration.
| Rule | File | Key Pattern |
|---|---|---|
| Schema Design | | Type-safe schema, DataLoader, union errors, Private fields |
| Patterns & Auth | | Permission classes, FastAPI integration, subscriptions |
基于Strawberry的代码优先GraphQL Schema,支持类型安全解析器与FastAPI集成。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| Schema设计 | | 类型安全Schema、DataLoader、联合错误、私有字段 |
| 模式与认证 | | 权限类、FastAPI集成、订阅功能 |
gRPC
gRPC
High-performance gRPC for internal microservice communication.
| Rule | File | Key Pattern |
|---|---|---|
| Service Definition | | Protobuf, async server, client timeout, code generation |
| Streaming & Interceptors | | Server/bidirectional streaming, auth, retry backoff |
用于内部微服务通信的高性能gRPC方案。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| 服务定义 | | Protobuf、异步服务器、客户端超时、代码生成 |
| 流处理与拦截器 | | 服务端/双向流、认证、重试退避 |
Streaming
流处理
Real-time data streaming with SSE, WebSockets, and proper cleanup.
| Rule | File | Key Pattern |
|---|---|---|
| SSE | | SSE endpoints, LLM streaming, reconnection, keepalive |
| WebSocket | | Bidirectional, heartbeat, aclosing(), backpressure |
基于SSE、WebSocket的实时数据流方案及正确的资源清理机制。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| SSE | | SSE端点、LLM流处理、重连、保活机制 |
| WebSocket | | 双向通信、心跳、aclosing()、背压处理 |
Quick Start Example
快速开始示例
python
undefinedpython
undefinedREST endpoint with versioning and RFC 9457 errors
带版本控制和RFC 9457错误处理的REST端点
from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
router = APIRouter()
@router.get("/api/v1/users/{user_id}")
async def get_user(user_id: str, service: UserService = Depends()):
user = await service.get_user(user_id)
if not user:
raise NotFoundProblem(
resource="User",
resource_id=user_id,
)
return UserResponseV1(id=user.id, name=user.full_name)
undefinedfrom fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
router = APIRouter()
@router.get("/api/v1/users/{user_id}")
async def get_user(user_id: str, service: UserService = Depends()):
user = await service.get_user(user_id)
if not user:
raise NotFoundProblem(
resource="User",
resource_id=user_id,
)
return UserResponseV1(id=user.id, name=user.full_name)
undefinedKey Decisions
关键决策
| Decision | Recommendation |
|---|---|
| Versioning strategy | URL path ( |
| Resource naming | Plural nouns, kebab-case |
| Pagination | Cursor-based for large datasets |
| Error format | RFC 9457 Problem Details with |
| Error type URI | Your API domain + |
| Support window | Current + 1 previous version |
| Deprecation notice | 3 months minimum before sunset |
| Sunset period | 6 months after deprecation |
| GraphQL schema | Code-first with Strawberry types |
| N+1 prevention | DataLoader for all nested resolvers |
| GraphQL auth | Permission classes (context-based) |
| gRPC proto | One service per file, shared common.proto |
| gRPC streaming | Server stream for lists, bidirectional for real-time |
| SSE keepalive | Every 30 seconds |
| WebSocket heartbeat | ping-pong every 30 seconds |
| Async generator cleanup | aclosing() for all external resources |
| 决策项 | 推荐方案 |
|---|---|
| 版本控制策略 | 面向公开API使用URL路径前缀( |
| 资源命名 | 复数名词、短横线分隔(kebab-case) |
| 分页方案 | 针对大数据集使用基于游标(Cursor-based)的分页 |
| 错误格式 | 采用RFC 9457 Problem Details,使用 |
| 错误类型URI | 你的API域名 + |
| 版本支持窗口 | 当前版本 + 前一个版本 |
| 废弃通知周期 | 下线前至少3个月通知 |
| 下线过渡期 | 废弃后保留6个月 |
| GraphQL Schema | 使用Strawberry类型的代码优先方案 |
| N+1问题预防 | 所有嵌套解析器使用DataLoader |
| GraphQL认证 | 基于上下文的权限类 |
| gRPC Protobuf | 每个服务对应一个文件,共享common.proto |
| gRPC流处理 | 列表数据使用服务端流,实时场景使用双向流 |
| SSE保活 | 每30秒发送一次 |
| WebSocket心跳 | 每30秒发送一次ping-pong |
| 异步生成器清理 | 对所有外部资源使用aclosing() |
Common Mistakes
常见误区
- Verbs in URLs (instead of
POST /createUser)POST /users - Inconsistent error formats across endpoints
- Breaking contracts without version bump
- Plain text error responses instead of Problem Details
- Sunsetting versions without deprecation headers
- Exposing internal details (stack traces, DB errors) in errors
- Missing on error responses
Content-Type: application/problem+json - Supporting too many concurrent API versions (max 2-3)
- Caching without considering version isolation
- URL中使用动词(如用替代
POST /createUser)POST /users - 不同端点的错误格式不一致
- 未升级版本就破坏契约
- 使用纯文本错误响应而非Problem Details
- 未添加废弃请求头就直接下线版本
- 错误中暴露内部细节(如栈跟踪、数据库错误)
- 错误响应缺少头
Content-Type: application/problem+json - 支持过多并发API版本(最多2-3个)
- 缓存未考虑版本隔离
Evaluations
测试用例
See for 9 test cases across all categories.
test-cases.json查看获取全类别的9个测试用例。
test-cases.jsonRelated Skills
相关技能
- - FastAPI-specific implementation patterns
fastapi-advanced - - Advanced rate limiting implementations and algorithms
rate-limiting - - Version usage metrics and error tracking
observability-monitoring - - Validation patterns beyond API error handling
input-validation - - SSE and WebSocket patterns for real-time APIs
streaming-api-patterns
- - FastAPI专属实现模式
fastapi-advanced - - 高级限流实现与算法
rate-limiting - - 版本使用指标与错误追踪
observability-monitoring - - 超越API错误处理的校验模式
input-validation - - 实时API的SSE与WebSocket模式
streaming-api-patterns
Capability Details
能力细节
rest-design
rest-design
Keywords: rest, restful, http, endpoint, route, path, resource, CRUD
Solves:
- How do I design RESTful APIs?
- REST endpoint patterns and conventions
- HTTP methods and status codes
关键词: rest, restful, http, endpoint, route, path, resource, CRUD
解决问题:
- 如何设计RESTful API?
- REST端点模式与规范
- HTTP方法与状态码
graphql-design
graphql-design
Keywords: graphql, schema, query, mutation, connection, relay
Solves:
- How do I design GraphQL APIs?
- Schema design best practices
- Connection pattern for pagination
Keywords: graphql, schema, query, mutation, connection, relay
解决问题:
- 如何设计GraphQL API?
- Schema设计最佳实践
- 基于Connection模式的分页
endpoint-design
endpoint-design
Keywords: endpoint, route, path, resource, CRUD, openapi
Solves:
- How do I structure API endpoints?
- What's the best URL pattern for this resource?
- RESTful endpoint naming conventions
Keywords: endpoint, route, path, resource, CRUD, openapi
解决问题:
- 如何结构化API端点?
- 该资源的最佳URL模式是什么?
- RESTful端点命名规范
url-versioning
url-versioning
Keywords: url version, path version, /v1/, /v2/
Solves:
- How to version REST APIs?
- URL-based API versioning
Keywords: url version, path version, /v1/, /v2/
解决问题:
- 如何对REST API进行版本控制?
- 基于URL的API版本控制
header-versioning
header-versioning
Keywords: header version, X-API-Version, content negotiation
Solves:
- Clean URL versioning
- Header-based API version
Keywords: header version, X-API-Version, content negotiation
解决问题:
- 无侵入式URL版本控制
- 基于请求头的API版本控制
deprecation
deprecation
Keywords: deprecation, sunset, version lifecycle, backward compatible
Solves:
- How to deprecate API versions?
- Version sunset policy
- Breaking vs non-breaking changes
Keywords: deprecation, sunset, version lifecycle, backward compatible
解决问题:
- 如何废弃API版本?
- 版本下线政策
- 破坏性变更与非破坏性变更
problem-details
problem-details
Keywords: problem details, RFC 9457, RFC 7807, structured error, application/problem+json
Solves:
- How to standardize API error responses?
- What format for API errors?
Keywords: problem details, RFC 9457, RFC 7807, structured error, application/problem+json
解决问题:
- 如何标准化API错误响应?
- API错误应采用什么格式?
validation-errors
validation-errors
Keywords: validation, field error, 422, unprocessable, pydantic
Solves:
- How to handle validation errors in APIs?
- Field-level error responses
Keywords: validation, field error, 422, unprocessable, pydantic
解决问题:
- 如何处理API中的校验错误?
- 字段级错误响应
error-registry
error-registry
Keywords: error registry, problem types, error catalog, error codes
Solves:
- How to document all API errors?
- Error type management
Keywords: error registry, problem types, error catalog, error codes
解决问题:
- 如何记录所有API错误?
- 错误类型管理