API设计模式技能Skill implementing-api-patterns

这个技能用于设计和实现高效、可扩展的API,涵盖REST、GraphQL、gRPC和tRPC等多种模式,适用于后端服务开发、公共API构建和微服务通信。关键词包括API设计、性能优化、类型安全、OpenAPI文档生成、分页策略和速率限制。

后端开发 0 次安装 0 次浏览 更新于 3/23/2026

名称: 实施API模式 描述: API设计和实现,涵盖REST、GraphQL、gRPC和tRPC模式。用于构建后端服务、公共API或服务间通信。涵盖REST框架(FastAPI、Axum、Gin、Hono)、GraphQL库(Strawberry、async-graphql、gqlgen、Pothos)、gRPC(Tonic、Connect-Go)、TypeScript的tRPC、分页策略(基于游标、基于偏移)、速率限制、缓存、版本控制和OpenAPI文档生成。包括前端集成模式,如表单、表格、仪表盘和AI聊天技能。

API模式技能

目的

根据用例,使用最优模式和框架设计和实现API。基于API消费者、性能需求和类型安全需求,在REST、GraphQL、gRPC和tRPC之间选择。

何时使用此技能

使用场景:

  • 为Web、移动或服务消费者构建后端API
  • 连接前端组件(表单、表格、仪表盘)到数据库
  • 实现分页、速率限制或缓存策略
  • 自动生成OpenAPI文档
  • 在REST、GraphQL、gRPC或tRPC模式之间选择
  • 集成认证和授权
  • 优化API性能和可扩展性

快速决策框架

谁消费您的API?
├─ 公共/第三方开发者 → 带OpenAPI的REST
│  ├─ Python → FastAPI(自动文档,40k请求/秒)
│  ├─ TypeScript → Hono(边缘优先,50k请求/秒,14KB)
│  ├─ Rust → Axum(140k请求/秒,<1ms延迟)
│  └─ Go → Gin(100k+请求/秒,成熟生态系统)
│
├─ 前端团队(同一组织)
│  ├─ TypeScript全栈? → tRPC(端到端类型安全)
│  └─ 复杂数据需求? → GraphQL
│      ├─ Python → Strawberry
│      ├─ Rust → async-graphql
│      ├─ Go → gqlgen
│      └─ TypeScript → Pothos
│
├─ 服务间通信(微服务)
│  └─ 高性能 → gRPC
│      ├─ Rust → Tonic
│      ├─ Go → Connect-Go(浏览器友好)
│      └─ Python → grpcio
│
└─ 移动应用
   ├─ 带宽受限 → GraphQL(仅请求所需字段)
   └─ 简单CRUD → REST(标准,易于理解)

REST框架选择

Python: FastAPI(推荐)

关键特性: 自动OpenAPI文档,Pydantic v2验证,异步/等待,40k请求/秒

基本示例:

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()}

参见references/rest-design-principles.md获取FastAPI模式和examples/python-fastapi/

TypeScript: Hono(边缘优先)

关键特性: 14KB包,可在任何运行时(Node/Deno/Bun/边缘)运行,Zod验证,50k请求/秒

基本示例:

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') }))

参见references/rest-design-principles.md获取Hono模式和examples/typescript-hono/

TypeScript: tRPC(全栈类型安全)

关键特性: 零代码生成,端到端类型安全,React Query集成,WebSocket订阅

基本示例:

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.md获取设置模式和examples/typescript-trpc/

Rust: Axum(高性能)

关键特性: Tower中间件,类型安全提取器,140k请求/秒,编译时验证

基本示例:

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 })
}

参见references/rest-design-principles.md获取Axum模式和examples/rust-axum/

Go: Gin(成熟生态系统)

关键特性: 最大Go生态系统,100k+请求/秒,结构体标签验证

基本示例:

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)
})

参见references/rest-design-principles.md获取Gin模式和examples/go-gin/

性能基准

语言 框架 请求/秒 延迟 冷启动 内存 最适合
Rust Actix-web ~150k <1ms N/A 2-5MB 最大吞吐量
Rust Axum ~140k <1ms N/A 2-5MB 易用性+性能
Go Gin ~100k+ 1-2ms N/A 5-10MB 成熟生态系统
TypeScript Hono ~50k <5ms <5ms 128MB 边缘部署
Python FastAPI ~40k 5-10ms 1-2s 30-50MB 开发者体验
TypeScript Express ~15k 10-20ms 1-3s 50-100MB 遗留系统

备注:

  • 基准假设单核,JSON响应
  • 实际性能随工作负载复杂度变化
  • 冷启动仅适用于无服务器/边缘部署

分页策略

基于游标(推荐)

优点: 处理实时变化,无跳过/重复记录,可扩展到数十亿记录

FastAPI示例:

@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
    }

基于偏移(仅适用于简单案例)

仅用于静态数据集(<10k记录)且需直接页面访问时使用。

参见references/pagination-patterns.md获取完整模式和前端集成。

OpenAPI文档

框架 OpenAPI支持 文档UI 配置
FastAPI 自动 Swagger UI + ReDoc 内置
Hono 中间件插件 Swagger UI @hono/swagger-ui
Axum utoipa crate Swagger UI 手动注解
Gin swaggo/swag Swagger UI 注释注解

FastAPI示例(零配置):

app = FastAPI(title="My API", version="1.0.0")

@app.post("/items", tags=["items"])
async def create_item(item: Item) -> Item:
    """创建带名称和价格的项"""
    return item
# 文档在 /docs, /redoc, /openapi.json

参见references/openapi-documentation.md获取框架特定设置。 使用scripts/generate_openapi.py以编程方式提取规范。

前端集成模式

表单 → REST POST/PUT

后端:

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()}

前端:

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)

表格 → GET带分页

参见基于游标分页示例和references/pagination-patterns.md

AI聊天 → SSE流传输

后端:

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())

前端:

const es = new EventSource('/api/chat')
es.addEventListener('message', (e) => appendToChat(e.data))

参见examples/获取与每个前端技能的完整集成示例。

速率限制

FastAPI示例(令牌桶):

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/分钟")
async def list_items():
    return {"items": []}

参见references/rate-limiting-strategies.md获取滑动窗口、分布式模式和Redis实现。

GraphQL库

当前端需要灵活数据获取或移动应用带宽受限时使用。

按语言:

  • Python: Strawberry 0.287(基于类型提示,异步)
  • Rust: async-graphql(高性能,tokio)
  • Go: gqlgen(从模式代码生成)
  • TypeScript: Pothos(类型安全构建器,无代码生成)

参见references/graphql-schema-design.md获取模式模式和N+1预防。 参见examples/graphql-strawberry/获取完整Python示例。

微服务gRPC

用于强类型和高性能的服务间通信。

按语言:

  • Rust: Tonic(异步,类型安全,代码生成)
  • Go: Connect-Go(gRPC兼容+浏览器友好)
  • Python: grpcio(官方实现)
  • TypeScript: @connectrpc/connect(浏览器+Node.js)

参见references/grpc-protobuf-guide.md获取Protocol Buffers指南。 参见examples/grpc-tonic/获取完整Rust示例。

附加资源

参考

  • references/rest-design-principles.md - REST资源建模,HTTP方法,状态码
  • references/graphql-schema-design.md - 模式模式,解析器优化,N+1预防
  • references/grpc-protobuf-guide.md - Proto3语法,服务定义,流传输
  • references/trpc-setup-guide.md - 路由器模式,中间件,Zod验证
  • references/pagination-patterns.md - 游标与偏移与数学解释
  • references/rate-limiting-strategies.md - 令牌桶,滑动窗口,Redis
  • references/caching-patterns.md - HTTP缓存,应用缓存策略
  • references/versioning-strategies.md - URI、头部、媒体类型版本控制
  • references/openapi-documentation.md - Swagger/OpenAPI最佳实践按框架

脚本(无令牌执行)

  • scripts/generate_openapi.py - 从代码生成OpenAPI规范
  • scripts/validate_api_spec.py - 验证OpenAPI 3.1合规性
  • scripts/benchmark_endpoints.py - 负载测试API端点

示例

  • examples/python-fastapi/ - 完整FastAPI REST API
  • examples/typescript-hono/ - Hono边缘优先API
  • examples/typescript-trpc/ - tRPC端到端类型安全API
  • examples/rust-axum/ - Axum REST API
  • examples/go-gin/ - Gin REST API
  • examples/graphql-strawberry/ - Python GraphQL
  • examples/grpc-tonic/ - Rust gRPC

快速参考

选择REST当: 公共API,标准CRUD,需要缓存,需要OpenAPI文档 选择GraphQL当: 前端需要灵活查询,移动带宽受限,复杂嵌套数据 选择gRPC当: 服务间通信,高性能,双向流传输 选择tRPC当: TypeScript全栈,同一团队拥有前端+后端,端到端类型安全

分页: 生产规模始终使用基于游标,仅简单案例使用基于偏移 文档: 偏好带自动OpenAPI生成的框架(FastAPI,Hono) 性能: Rust(Axum)用于最大吞吐量,Go(Gin)用于成熟度,Python(FastAPI)用于开发者体验