api-design

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API 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
rules/
loaded on-demand.
涵盖REST/GraphQL框架设计、版本控制策略以及RFC 9457错误处理的全面API设计模式。每个类别在
rules/
目录下都有独立的规则文件,可按需加载。

Quick Reference

快速参考

CategoryRulesImpactWhen to Use
API Framework3HIGHREST conventions, resource modeling, OpenAPI specifications
Versioning3HIGHURL path versioning, header versioning, deprecation/sunset policies
Error Handling3HIGHRFC 9457 Problem Details, validation errors, error type registries
GraphQL2HIGHStrawberry code-first, DataLoader, permissions, subscriptions
gRPC2HIGHProtobuf services, streaming, interceptors, retry
Streaming2HIGHSSE endpoints, WebSocket bidirectional, async generators
Total: 15 rules across 6 categories
类别规则数量影响级别适用场景
API框架3REST规范、资源建模、OpenAPI规范
版本控制3URL路径版本控制、请求头版本控制、废弃/下线策略
错误处理3RFC 9457 Problem Details、校验错误、错误类型注册表
GraphQL2Strawberry代码优先、DataLoader、权限控制、订阅
gRPC2Protobuf服务、流处理、拦截器、重试机制
流处理2SSE端点、WebSocket双向通信、异步生成器
总计:6个类别共15条规则

API Framework

API框架

REST and GraphQL API design conventions for consistent, developer-friendly APIs.
RuleFileKey Pattern
REST Conventions
rules/framework-rest-conventions.md
Plural nouns, HTTP methods, status codes, pagination
Resource Modeling
rules/framework-resource-modeling.md
Hierarchical URLs, filtering, sorting, field selection
OpenAPI
rules/framework-openapi.md
OpenAPI 3.1 specs, documentation, schema definitions
用于构建一致、开发者友好型API的REST和GraphQL设计规范。
规则文件核心模式
REST规范
rules/framework-rest-conventions.md
复数名词、HTTP方法、状态码、分页
资源建模
rules/framework-resource-modeling.md
层级URL、过滤、排序、字段选择
OpenAPI
rules/framework-openapi.md
OpenAPI 3.1规范、文档、Schema定义

Versioning

版本控制

Strategies for API evolution without breaking clients.
RuleFileKey Pattern
URL Path
rules/versioning-url-path.md
/api/v1/
prefix routing, version-specific schemas
Header
rules/versioning-header.md
X-API-Version
header, content negotiation
Deprecation
rules/versioning-deprecation.md
Sunset headers, lifecycle management, breaking change policy
在不破坏客户端兼容性的前提下实现API演进的策略。
规则文件核心模式
URL路径版本
rules/versioning-url-path.md
/api/v1/
前缀路由、版本专属Schema
请求头版本
rules/versioning-header.md
X-API-Version
请求头、内容协商
废弃策略
rules/versioning-deprecation.md
Sunset请求头、生命周期管理、破坏性变更政策

Error Handling

错误处理

RFC 9457 Problem Details for machine-readable, standardized error responses.
RuleFileKey Pattern
Problem Details
rules/errors-problem-details.md
RFC 9457 schema,
application/problem+json
, exception classes
Validation
rules/errors-validation.md
Field-level errors, Pydantic integration, 422 responses
Error Catalog
rules/errors-error-catalog.md
Problem type registry, error type URIs, client handling
基于RFC 9457 Problem Details的机器可读标准化错误响应方案。
规则文件核心模式
Problem Details
rules/errors-problem-details.md
RFC 9457 Schema、
application/problem+json
、异常类
校验错误
rules/errors-validation.md
字段级错误、Pydantic集成、422响应
错误目录
rules/errors-error-catalog.md
Problem类型注册表、错误类型URI、客户端处理

GraphQL

GraphQL

Strawberry GraphQL code-first schema with type-safe resolvers and FastAPI integration.
RuleFileKey Pattern
Schema Design
rules/graphql-strawberry.md
Type-safe schema, DataLoader, union errors, Private fields
Patterns & Auth
rules/graphql-schema.md
Permission classes, FastAPI integration, subscriptions
基于Strawberry的代码优先GraphQL Schema,支持类型安全解析器与FastAPI集成。
规则文件核心模式
Schema设计
rules/graphql-strawberry.md
类型安全Schema、DataLoader、联合错误、私有字段
模式与认证
rules/graphql-schema.md
权限类、FastAPI集成、订阅功能

gRPC

gRPC

High-performance gRPC for internal microservice communication.
RuleFileKey Pattern
Service Definition
rules/grpc-service.md
Protobuf, async server, client timeout, code generation
Streaming & Interceptors
rules/grpc-streaming.md
Server/bidirectional streaming, auth, retry backoff
用于内部微服务通信的高性能gRPC方案。
规则文件核心模式
服务定义
rules/grpc-service.md
Protobuf、异步服务器、客户端超时、代码生成
流处理与拦截器
rules/grpc-streaming.md
服务端/双向流、认证、重试退避

Streaming

流处理

Real-time data streaming with SSE, WebSockets, and proper cleanup.
RuleFileKey Pattern
SSE
rules/streaming-sse.md
SSE endpoints, LLM streaming, reconnection, keepalive
WebSocket
rules/streaming-websocket.md
Bidirectional, heartbeat, aclosing(), backpressure
基于SSE、WebSocket的实时数据流方案及正确的资源清理机制。
规则文件核心模式
SSE
rules/streaming-sse.md
SSE端点、LLM流处理、重连、保活机制
WebSocket
rules/streaming-websocket.md
双向通信、心跳、aclosing()、背压处理

Quick Start Example

快速开始示例

python
undefined
python
undefined

REST 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)
undefined
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)
undefined

Key Decisions

关键决策

DecisionRecommendation
Versioning strategyURL path (
/api/v1/
) for public APIs
Resource namingPlural nouns, kebab-case
PaginationCursor-based for large datasets
Error formatRFC 9457 Problem Details with
application/problem+json
Error type URIYour API domain +
/problems/
prefix
Support windowCurrent + 1 previous version
Deprecation notice3 months minimum before sunset
Sunset period6 months after deprecation
GraphQL schemaCode-first with Strawberry types
N+1 preventionDataLoader for all nested resolvers
GraphQL authPermission classes (context-based)
gRPC protoOne service per file, shared common.proto
gRPC streamingServer stream for lists, bidirectional for real-time
SSE keepaliveEvery 30 seconds
WebSocket heartbeatping-pong every 30 seconds
Async generator cleanupaclosing() for all external resources
决策项推荐方案
版本控制策略面向公开API使用URL路径前缀(
/api/v1/
资源命名复数名词、短横线分隔(kebab-case)
分页方案针对大数据集使用基于游标(Cursor-based)的分页
错误格式采用RFC 9457 Problem Details,使用
application/problem+json
类型
错误类型URI你的API域名 +
/problems/
前缀
版本支持窗口当前版本 + 前一个版本
废弃通知周期下线前至少3个月通知
下线过渡期废弃后保留6个月
GraphQL Schema使用Strawberry类型的代码优先方案
N+1问题预防所有嵌套解析器使用DataLoader
GraphQL认证基于上下文的权限类
gRPC Protobuf每个服务对应一个文件,共享common.proto
gRPC流处理列表数据使用服务端流,实时场景使用双向流
SSE保活每30秒发送一次
WebSocket心跳每30秒发送一次ping-pong
异步生成器清理对所有外部资源使用aclosing()

Common Mistakes

常见误区

  1. Verbs in URLs (
    POST /createUser
    instead of
    POST /users
    )
  2. Inconsistent error formats across endpoints
  3. Breaking contracts without version bump
  4. Plain text error responses instead of Problem Details
  5. Sunsetting versions without deprecation headers
  6. Exposing internal details (stack traces, DB errors) in errors
  7. Missing
    Content-Type: application/problem+json
    on error responses
  8. Supporting too many concurrent API versions (max 2-3)
  9. Caching without considering version isolation
  1. URL中使用动词(如用
    POST /createUser
    替代
    POST /users
  2. 不同端点的错误格式不一致
  3. 未升级版本就破坏契约
  4. 使用纯文本错误响应而非Problem Details
  5. 未添加废弃请求头就直接下线版本
  6. 错误中暴露内部细节(如栈跟踪、数据库错误)
  7. 错误响应缺少
    Content-Type: application/problem+json
  8. 支持过多并发API版本(最多2-3个)
  9. 缓存未考虑版本隔离

Evaluations

测试用例

See
test-cases.json
for 9 test cases across all categories.
查看
test-cases.json
获取全类别的9个测试用例。

Related Skills

相关技能

  • fastapi-advanced
    - FastAPI-specific implementation patterns
  • rate-limiting
    - Advanced rate limiting implementations and algorithms
  • observability-monitoring
    - Version usage metrics and error tracking
  • input-validation
    - Validation patterns beyond API error handling
  • streaming-api-patterns
    - SSE and WebSocket patterns for real-time APIs
  • fastapi-advanced
    - FastAPI专属实现模式
  • rate-limiting
    - 高级限流实现与算法
  • observability-monitoring
    - 版本使用指标与错误追踪
  • input-validation
    - 超越API错误处理的校验模式
  • streaming-api-patterns
    - 实时API的SSE与WebSocket模式

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错误?
  • 错误类型管理