implementing-api-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Patterns Skill
API模式技能
Purpose
用途
Design and implement APIs using the optimal pattern and framework for the use case. Choose between REST, GraphQL, gRPC, and tRPC based on API consumers, performance requirements, and type safety needs.
根据使用场景选择最优模式与框架来设计和实现API。可根据API使用者、性能要求和类型安全需求,在REST、GraphQL、gRPC和tRPC之间进行选择。
When to Use This Skill
适用场景
Use when:
- Building backend APIs for web, mobile, or service consumers
- Connecting frontend components (forms, tables, dashboards) to databases
- Implementing pagination, rate limiting, or caching strategies
- Generating OpenAPI documentation automatically
- Choosing between REST, GraphQL, gRPC, or tRPC patterns
- Integrating authentication and authorization
- Optimizing API performance and scalability
适用于以下情况:
- 为网页、移动端或服务消费者构建后端API
- 将前端组件(表单、表格、仪表盘)与数据库连接
- 实现分页、限流或缓存策略
- 自动生成OpenAPI文档
- 在REST、GraphQL、gRPC或tRPC模式间做选择
- 集成认证与授权功能
- 优化API性能与可扩展性
Quick Decision Framework
快速决策框架
WHO CONSUMES YOUR API?
├─ PUBLIC/THIRD-PARTY DEVELOPERS → REST with OpenAPI
│ ├─ Python → FastAPI (auto-docs, 40k req/s)
│ ├─ TypeScript → Hono (edge-first, 50k req/s, 14KB)
│ ├─ Rust → Axum (140k req/s, <1ms latency)
│ └─ Go → Gin (100k+ req/s, mature ecosystem)
│
├─ FRONTEND TEAM (same org)
│ ├─ TypeScript full-stack? → tRPC (E2E type safety)
│ └─ Complex data needs? → GraphQL
│ ├─ Python → Strawberry
│ ├─ Rust → async-graphql
│ ├─ Go → gqlgen
│ └─ TypeScript → Pothos
│
├─ SERVICE-TO-SERVICE (microservices)
│ └─ High performance → gRPC
│ ├─ Rust → Tonic
│ ├─ Go → Connect-Go (browser-friendly)
│ └─ Python → grpcio
│
└─ MOBILE APPS
├─ Bandwidth constrained → GraphQL (request only needed fields)
└─ Simple CRUD → REST (standard, well-understood)你的API使用者是谁?
├─ 公开/第三方开发者 → 搭配OpenAPI的REST
│ ├─ Python → FastAPI(自动文档,4万请求/秒)
│ ├─ TypeScript → Hono(边缘优先,5万请求/秒,体积14KB)
│ ├─ Rust → Axum(14万请求/秒,延迟<1ms)
│ └─ Go → Gin(10万+请求/秒,生态成熟)
│
├─ 前端团队(同一组织)
│ ├─ TypeScript全栈? → tRPC(端到端类型安全)
│ └─ 复杂数据需求? → GraphQL
│ ├─ Python → Strawberry
│ ├─ Rust → async-graphql
│ ├─ Go → gqlgen
│ └─ TypeScript → Pothos
│
├─ 服务间通信(微服务)
│ └─ 高性能需求 → gRPC
│ ├─ Rust → Tonic
│ ├─ Go → Connect-Go(浏览器友好)
│ └─ Python → grpcio
│
└─ 移动应用
├─ 带宽受限 → GraphQL(仅请求所需字段)
└─ 简单CRUD操作 → REST(标准通用,易于理解)REST Framework Selection
REST框架选择
Python: FastAPI (Recommended)
Python: FastAPI(推荐)
Key Features: Auto OpenAPI docs, Pydantic v2 validation, async/await, 40k req/s
Basic Example:
python
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.post("/items")
async def create_item(item: Item):
return {"id": 1, **item.dict()}See for FastAPI patterns and .
references/rest-design-principles.mdexamples/python-fastapi/核心特性: 自动生成OpenAPI文档、Pydantic v2验证、async/await支持、4万请求/秒
基础示例:
python
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.post("/items")
async def create_item(item: Item):
return {"id": 1, **item.dict()}查看获取FastAPI相关模式,示例代码见。
references/rest-design-principles.mdexamples/python-fastapi/TypeScript: Hono (Edge-First)
TypeScript: Hono(边缘优先)
Key Features: 14KB bundle, runs on any runtime (Node/Deno/Bun/edge), Zod validation, 50k req/s
Basic Example:
typescript
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { z } from 'zod'
const app = new Hono()
app.post('/items', zValidator('json', z.object({
name: z.string(), price: z.number()
})), (c) => c.json({ id: 1, ...c.req.valid('json') }))See for Hono patterns and .
references/rest-design-principles.mdexamples/typescript-hono/核心特性: 14KB包体积、支持所有运行时(Node/Deno/Bun/边缘环境)、Zod验证、5万请求/秒
基础示例:
typescript
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { z } from 'zod'
const app = new Hono()
app.post('/items', zValidator('json', z.object({
name: z.string(), price: z.number()
})), (c) => c.json({ id: 1, ...c.req.valid('json') }))查看获取Hono相关模式,示例代码见。
references/rest-design-principles.mdexamples/typescript-hono/TypeScript: tRPC (Full-Stack Type Safety)
TypeScript: tRPC(全栈类型安全)
Key Features: Zero codegen, E2E type safety, React Query integration, WebSocket subscriptions
Basic Example:
typescript
import { initTRPC } from '@trpc/server'
import { z } from 'zod'
const t = initTRPC.create()
export const appRouter = t.router({
createItem: t.procedure
.input(z.object({ name: z.string(), price: z.number() }))
.mutation(({ input }) => ({ id: '1', ...input }))
})
export type AppRouter = typeof appRouterSee for setup patterns and .
references/trpc-setup-guide.mdexamples/typescript-trpc/核心特性: 无需代码生成、端到端类型安全、React Query集成、WebSocket订阅支持
基础示例:
typescript
import { initTRPC } from '@trpc/server'
import { z } from 'zod'
const t = initTRPC.create()
export const appRouter = t.router({
createItem: t.procedure
.input(z.object({ name: z.string(), price: z.number() }))
.mutation(({ input }) => ({ id: '1', ...input }))
})
export type AppRouter = typeof appRouter查看获取配置模式,示例代码见。
references/trpc-setup-guide.mdexamples/typescript-trpc/Rust: Axum (High Performance)
Rust: Axum(高性能)
Key Features: Tower middleware, type-safe extractors, 140k req/s, compile-time verification
Basic Example:
rust
use axum::{routing::post, Json, Router};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct CreateItem { name: String, price: f64 }
#[derive(Serialize)]
struct Item { id: u64, name: String, price: f64 }
async fn create_item(Json(payload): Json<CreateItem>) -> Json<Item> {
Json(Item { id: 1, name: payload.name, price: payload.price })
}See for Axum patterns and .
references/rest-design-principles.mdexamples/rust-axum/核心特性: Tower中间件、类型安全提取器、14万请求/秒、编译时验证
基础示例:
rust
use axum::{routing::post, Json, Router};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct CreateItem { name: String, price: f64 }
#[derive(Serialize)]
struct Item { id: u64, name: String, price: f64 }
async fn create_item(Json(payload): Json<CreateItem>) -> Json<Item> {
Json(Item { id: 1, name: payload.name, price: payload.price })
}查看获取Axum相关模式,示例代码见。
references/rest-design-principles.mdexamples/rust-axum/Go: Gin (Mature Ecosystem)
Go: Gin(成熟生态)
Key Features: Largest Go ecosystem, 100k+ req/s, struct tag validation
Basic Example:
go
type Item struct {
Name string `json:"name" binding:"required"`
Price float64 `json:"price" binding:"required,gt=0"`
}
r := gin.Default()
r.POST("/items", func(c *gin.Context) {
var item Item
if c.ShouldBindJSON(&item); err != nil {
c.JSON(400, gin.H{"error": err.Error()}); return
}
c.JSON(201, item)
})See for Gin patterns and .
references/rest-design-principles.mdexamples/go-gin/核心特性: 最大的Go语言生态、10万+请求/秒、结构体标签验证
基础示例:
go
type Item struct {
Name string `json:"name" binding:"required"`
Price float64 `json:"price" binding:"required,gt=0"`
}
r := gin.Default()
r.POST("/items", func(c *gin.Context) {
var item Item
if err := c.ShouldBindJSON(&item); err != nil {
c.JSON(400, gin.H{"error": err.Error()}); return
}
c.JSON(201, item)
})查看获取Gin相关模式,示例代码见。
references/rest-design-principles.mdexamples/go-gin/Performance Benchmarks
性能基准测试
| Language | Framework | Req/s | Latency | Cold Start | Memory | Best For |
|---|---|---|---|---|---|---|
| Rust | Actix-web | ~150k | <1ms | N/A | 2-5MB | Maximum throughput |
| Rust | Axum | ~140k | <1ms | N/A | 2-5MB | Ergonomics + performance |
| Go | Gin | ~100k+ | 1-2ms | N/A | 5-10MB | Mature ecosystem |
| TypeScript | Hono | ~50k | <5ms | <5ms | 128MB | Edge deployment |
| Python | FastAPI | ~40k | 5-10ms | 1-2s | 30-50MB | Developer experience |
| TypeScript | Express | ~15k | 10-20ms | 1-3s | 50-100MB | Legacy systems |
Notes:
- Benchmarks assume single-core, JSON responses
- Actual performance varies with workload complexity
- Cold start only applies to serverless/edge deployments
| 语言 | 框架 | 请求/秒 | 延迟 | 冷启动 | 内存 | 适用场景 |
|---|---|---|---|---|---|---|
| Rust | Actix-web | ~15万 | <1ms | 无 | 2-5MB | 最大吞吐量 |
| Rust | Axum | ~14万 | <1ms | 无 | 2-5MB | 易用性+性能兼顾 |
| Go | Gin | ~10万+ | 1-2ms | 无 | 5-10MB | 成熟生态 |
| TypeScript | Hono | ~5万 | <5ms | <5ms | 128MB | 边缘部署 |
| Python | FastAPI | ~4万 | 5-10ms | 1-2s | 30-50MB | 开发者体验 |
| TypeScript | Express | ~1.5万 | 10-20ms | 1-3s | 50-100MB | 遗留系统 |
说明:
- 基准测试基于单核、JSON响应场景
- 实际性能随工作负载复杂度变化
- 冷启动仅适用于无服务器/边缘部署场景
Pagination Strategies
分页策略
Cursor-Based (Recommended)
基于游标(推荐)
Advantages: Handles real-time changes, no skipped/duplicate records, scales to billions
FastAPI Example:
python
@app.get("/items")
async def list_items(cursor: Optional[str] = None, limit: int = 20):
query = db.query(Item).filter(Item.id > cursor) if cursor else db.query(Item)
items = query.limit(limit).all()
return {
"items": items,
"next_cursor": items[-1].id if items else None,
"has_more": len(items) == limit
}优势: 支持实时数据变更、无记录遗漏/重复、可扩展至数十亿条数据
FastAPI示例:
python
@app.get("/items")
async def list_items(cursor: Optional[str] = None, limit: int = 20):
query = db.query(Item).filter(Item.id > cursor) if cursor else db.query(Item)
items = query.limit(limit).all()
return {
"items": items,
"next_cursor": items[-1].id if items else None,
"has_more": len(items) == limit
}Offset-Based (Simple Cases Only)
基于偏移量(仅适用于简单场景)
Use only for static datasets (<10k records) with direct page access needs.
See for complete patterns and frontend integration.
references/pagination-patterns.md仅适用于静态数据集(<1万条记录)且需要直接页面访问的场景。
查看获取完整模式及前端集成方案。
references/pagination-patterns.mdOpenAPI Documentation
OpenAPI文档
| Framework | OpenAPI Support | Docs UI | Configuration |
|---|---|---|---|
| FastAPI | Automatic | Swagger UI + ReDoc | Built-in |
| Hono | Middleware plugin | Swagger UI | |
| Axum | utoipa crate | Swagger UI | Manual annotations |
| Gin | swaggo/swag | Swagger UI | Comment annotations |
FastAPI Example (Zero Config):
python
app = FastAPI(title="My API", version="1.0.0")
@app.post("/items", tags=["items"])
async def create_item(item: Item) -> Item:
"""Create item with name and price"""
return item| 框架 | OpenAPI支持 | 文档UI | 配置方式 |
|---|---|---|---|
| FastAPI | 自动生成 | Swagger UI + ReDoc | 内置支持 |
| Hono | 中间件插件 | Swagger UI | |
| Axum | utoipa crate | Swagger UI | 手动注解 |
| Gin | swaggo/swag | Swagger UI | 注释注解 |
FastAPI示例(零配置):
python
app = FastAPI(title="My API", version="1.0.0")
@app.post("/items", tags=["items"])
async def create_item(item: Item) -> Item:
"""创建包含名称和价格的商品"""
return itemDocs at /docs, /redoc, /openapi.json
文档访问地址:/docs, /redoc, /openapi.json
See `references/openapi-documentation.md` for framework-specific setup.
Use `scripts/generate_openapi.py` to extract specs programmatically.
查看`references/openapi-documentation.md`获取各框架的具体配置方法。
使用`scripts/generate_openapi.py`以编程方式提取规范。Frontend Integration Patterns
前端集成模式
Forms → REST POST/PUT
表单 → REST POST/PUT
Backend:
python
class UserCreate(BaseModel):
email: EmailStr; name: str; age: int
@app.post("/api/users", status_code=201)
async def create_user(user: UserCreate):
return {"id": 1, **user.dict()}Frontend:
typescript
const res = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
if (!res.ok) throw new Error((await res.json()).detail)后端:
python
class UserCreate(BaseModel):
email: EmailStr; name: str; age: int
@app.post("/api/users", status_code=201)
async def create_user(user: UserCreate):
return {"id": 1, **user.dict()}前端:
typescript
const res = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
if (!res.ok) throw new Error((await res.json()).detail)Tables → GET with Pagination
表格 → 带分页的GET请求
See cursor pagination example above and .
references/pagination-patterns.md参考上述游标分页示例及。
references/pagination-patterns.mdAI Chat → SSE Streaming
AI聊天 → SSE流式传输
Backend:
python
from sse_starlette.sse import EventSourceResponse
@app.post("/api/chat")
async def chat(message: str):
async def gen():
for chunk in llm_stream(message):
yield {"event": "message", "data": chunk}
return EventSourceResponse(gen())Frontend:
typescript
const es = new EventSource('/api/chat')
es.addEventListener('message', (e) => appendToChat(e.data))See for complete integration examples with each frontend skill.
examples/后端:
python
from sse_starlette.sse import EventSourceResponse
@app.post("/api/chat")
async def chat(message: str):
async def gen():
for chunk in llm_stream(message):
yield {"event": "message", "data": chunk}
return EventSourceResponse(gen())前端:
typescript
const es = new EventSource('/api/chat')
es.addEventListener('message', (e) => appendToChat(e.data))查看获取各前端技能的完整集成示例。
examples/Rate Limiting
限流
FastAPI Example (Token Bucket):
python
from slowapi import Limiter
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
@app.get("/items")
@limiter.limit("100/minute")
async def list_items():
return {"items": []}See for sliding window, distributed patterns, and Redis implementation.
references/rate-limiting-strategies.mdFastAPI示例(令牌桶算法):
python
from slowapi import Limiter
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
@app.get("/items")
@limiter.limit("100/minute")
async def list_items():
return {"items": []}查看获取滑动窗口、分布式模式及Redis实现方案。
references/rate-limiting-strategies.mdGraphQL Libraries
GraphQL库
Use when frontend needs flexible data fetching or mobile apps have bandwidth constraints.
By Language:
- Python: Strawberry 0.287 (type-hint-based, async)
- Rust: async-graphql (high performance, tokio)
- Go: gqlgen (code generation from schema)
- TypeScript: Pothos (type-safe builder, no codegen)
See for schema patterns and N+1 prevention.
See for complete Python example.
references/graphql-schema-design.mdexamples/graphql-strawberry/当前端需要灵活的数据获取或移动应用存在带宽限制时使用。
按语言分类:
- Python: Strawberry 0.287(基于类型提示,支持异步)
- Rust: async-graphql(高性能,基于tokio)
- Go: gqlgen(从Schema生成代码)
- TypeScript: Pothos(类型安全构建器,无需代码生成)
查看获取Schema模式及N+1问题解决方案。
查看获取完整Python示例。
references/graphql-schema-design.mdexamples/graphql-strawberry/gRPC for Microservices
微服务中的gRPC
Use for service-to-service communication with strong typing and high performance.
By Language:
- Rust: Tonic (async, type-safe, code generation)
- Go: Connect-Go (gRPC-compatible + browser-friendly)
- Python: grpcio (official implementation)
- TypeScript: @connectrpc/connect (browser + Node.js)
See for Protocol Buffers guide.
See for complete Rust example.
references/grpc-protobuf-guide.mdexamples/grpc-tonic/适用于服务间通信,具备强类型和高性能特性。
按语言分类:
- Rust: Tonic(异步、类型安全、代码生成)
- Go: Connect-Go(兼容gRPC+浏览器友好)
- Python: grpcio(官方实现)
- TypeScript: @connectrpc/connect(浏览器+Node.js支持)
查看获取Protocol Buffers指南。
查看获取完整Rust示例。
references/grpc-protobuf-guide.mdexamples/grpc-tonic/Additional Resources
额外资源
References
参考文档
- - REST resource modeling, HTTP methods, status codes
references/rest-design-principles.md - - Schema patterns, resolver optimization, N+1 prevention
references/graphql-schema-design.md - - Proto3 syntax, service definitions, streaming
references/grpc-protobuf-guide.md - - Router patterns, middleware, Zod validation
references/trpc-setup-guide.md - - Cursor vs offset with mathematical explanation
references/pagination-patterns.md - - Token bucket, sliding window, Redis
references/rate-limiting-strategies.md - - HTTP caching, application caching strategies
references/caching-patterns.md - - URI, header, media type versioning
references/versioning-strategies.md - - Swagger/OpenAPI best practices by framework
references/openapi-documentation.md
- - REST资源建模、HTTP方法、状态码
references/rest-design-principles.md - - Schema模式、解析器优化、N+1问题预防
references/graphql-schema-design.md - - Proto3语法、服务定义、流式传输
references/grpc-protobuf-guide.md - - 路由模式、中间件、Zod验证
references/trpc-setup-guide.md - - 游标与偏移量的对比及数学解释
references/pagination-patterns.md - - 令牌桶、滑动窗口、Redis实现
references/rate-limiting-strategies.md - - HTTP缓存、应用层缓存策略
references/caching-patterns.md - - URI、请求头、媒体类型版本控制
references/versioning-strategies.md - - 各框架的Swagger/OpenAPI最佳实践
references/openapi-documentation.md
Scripts (Token-Free Execution)
脚本(无需令牌即可执行)
- - Generate OpenAPI spec from code
scripts/generate_openapi.py - - Validate OpenAPI 3.1 compliance
scripts/validate_api_spec.py - - Load test API endpoints
scripts/benchmark_endpoints.py
- - 从代码生成OpenAPI规范
scripts/generate_openapi.py - - 验证OpenAPI 3.1合规性
scripts/validate_api_spec.py - - 对API端点进行负载测试
scripts/benchmark_endpoints.py
Examples
示例代码
- - Complete FastAPI REST API
examples/python-fastapi/ - - Hono edge-first API
examples/typescript-hono/ - - tRPC E2E type-safe API
examples/typescript-trpc/ - - Axum REST API
examples/rust-axum/ - - Gin REST API
examples/go-gin/ - - Python GraphQL
examples/graphql-strawberry/ - - Rust gRPC
examples/grpc-tonic/
- - 完整FastAPI REST API
examples/python-fastapi/ - - Hono边缘优先API
examples/typescript-hono/ - - tRPC端到端类型安全API
examples/typescript-trpc/ - - Axum REST API
examples/rust-axum/ - - Gin REST API
examples/go-gin/ - - Python GraphQL示例
examples/graphql-strawberry/ - - Rust gRPC示例
examples/grpc-tonic/
Quick Reference
快速参考
Choose REST when: Public API, standard CRUD, need caching, OpenAPI docs required
Choose GraphQL when: Frontend needs flexible queries, mobile bandwidth constraints, complex nested data
Choose gRPC when: Service-to-service communication, high performance, bidirectional streaming
Choose tRPC when: TypeScript full-stack, same team owns frontend + backend, E2E type safety
Pagination: Always use cursor-based for production scale, offset-based only for simple cases
Documentation: Prefer frameworks with automatic OpenAPI generation (FastAPI, Hono)
Performance: Rust (Axum) for max throughput, Go (Gin) for maturity, Python (FastAPI) for DX
选择REST的场景: 公开API、标准CRUD操作、需要缓存、要求生成OpenAPI文档
选择GraphQL的场景: 前端需要灵活查询、移动应用带宽受限、复杂嵌套数据需求
选择gRPC的场景: 服务间通信、高性能需求、双向流式传输
选择tRPC的场景: TypeScript全栈、同一团队负责前后端、端到端类型安全
分页: 生产环境大规模场景始终使用基于游标分页,仅在简单场景使用基于偏移量分页
文档: 优先选择支持自动生成OpenAPI的框架(FastAPI、Hono)
性能: Rust(Axum)适用于最大吞吐量需求,Go(Gin)适用于成熟生态,Python(FastAPI)适用于开发者体验