api-design
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Design
API设计
Comprehensive API design skill combining REST, GraphQL, gRPC, and Python library architecture expertise. This merged skill provides patterns, templates, and tools for building production-grade APIs.
整合了 REST、GraphQL、gRPC 及 Python 库架构专业知识的综合性 API 设计技能。该合并技能为构建生产级 API 提供模式、模板和工具。
Overview
概述
This skill combines expertise from multiple specialized domains:
- REST API Design - Resource-oriented endpoints, HTTP semantics, OpenAPI specs
- GraphQL Development - Schema-first design, resolvers, federation, DataLoader
- gRPC Services - Protocol Buffers, streaming patterns
- Python Library Architecture - Package structure, API design, SOLID principles
- Security & Performance - OAuth, JWT, rate limiting, caching
Time Savings: 50%+ reduction in API development time through templates, code generation, and best practices.
本技能融合了多个专业领域的知识:
- REST API 设计 - 面向资源的端点、HTTP 语义、OpenAPI 规范
- GraphQL 开发 - 优先 schema 设计、解析器、联邦机制、DataLoader
- gRPC 服务 - Protocol Buffers、流式处理模式
- Python 库架构 - 包结构、API 设计、SOLID 原则
- 安全与性能 - OAuth、JWT、速率限制、缓存
时间节省: 通过模板、代码生成和最佳实践,可将 API 开发时间减少 50% 以上。
Quick Reference
快速参考
RESTful Resource Design
RESTful 资源设计
URL Patterns:
- (plural nouns, lowercase with hyphens)
/api/v1/users - (hierarchical, max 2 levels)
/api/v1/organizations/{org_id}/teams - Never use verbs: or underscores:
/getUsers/user_profiles
HTTP Methods:
- - Retrieve resources (safe, idempotent, cacheable)
GET - - Create new resources (returns 201 with Location header)
POST - - Replace entire resource (idempotent)
PUT - - Partial update (only changed fields)
PATCH - - Remove resource (idempotent, returns 204)
DELETE
URL 模式:
- (复数名词,小写连字符格式)
/api/v1/users - (层级结构,最多 2 级)
/api/v1/organizations/{org_id}/teams - 禁止使用动词:或下划线:
/getUsers/user_profiles
HTTP 方法:
- - 获取资源(安全、幂等、可缓存)
GET - - 创建新资源(返回 201 状态码及 Location 头部)
POST - - 替换整个资源(幂等)
PUT - - 部分更新(仅修改指定字段)
PATCH - - 删除资源(幂等,返回 204 状态码)
DELETE
HTTP Status Codes
HTTP 状态码
Success:
- - GET, PUT, PATCH success
200 OK - - POST success (include Location header)
201 Created - - DELETE success
204 No Content
Client Errors:
- - Malformed request
400 Bad Request - - Missing/invalid authentication
401 Unauthorized - - Insufficient permissions
403 Forbidden - - Resource doesn't exist
404 Not Found - - Duplicate resource
409 Conflict - - Validation errors
422 Unprocessable Entity - - Rate limit exceeded
429 Too Many Requests
Server Errors:
- - Unhandled exception
500 Internal Server Error - - Database/service down
503 Service Unavailable
成功:
- - GET、PUT、PATCH 请求成功
200 OK - - POST 请求成功(需包含 Location 头部)
201 Created - - DELETE 请求成功
204 No Content
客户端错误:
- - 请求格式错误
400 Bad Request - - 缺少/无效的认证信息
401 Unauthorized - - 权限不足
403 Forbidden - - 资源不存在
404 Not Found - - 资源重复
409 Conflict - - 验证错误
422 Unprocessable Entity - - 超出速率限制
429 Too Many Requests
服务器错误:
- - 未处理的异常
500 Internal Server Error - - 数据库/服务不可用
503 Service Unavailable
Error Response Format
错误响应格式
json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Request validation failed",
"details": [
{ "field": "email", "message": "Invalid email format" }
],
"requestId": "req_abc123",
"timestamp": "2025-10-25T10:30:00Z"
}
}json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Request validation failed",
"details": [
{ "field": "email", "message": "Invalid email format" }
],
"requestId": "req_abc123",
"timestamp": "2025-10-25T10:30:00Z"
}
}GraphQL Schema Design
GraphQL Schema 设计
graphql
type User {
id: ID!
email: String!
profile: Profile
posts(first: Int, after: String): PostConnection!
createdAt: DateTime!
}
type PostConnection {
edges: [PostEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
type Query {
user(id: ID!): User
users(first: Int, after: String): UserConnection!
me: User
}
type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
updateUser(id: ID!, input: UpdateUserInput!): UpdateUserPayload!
}graphql
type User {
id: ID!
email: String!
profile: Profile
posts(first: Int, after: String): PostConnection!
createdAt: DateTime!
}
type PostConnection {
edges: [PostEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
type Query {
user(id: ID!): User
users(first: Int, after: String): UserConnection!
me: User
}
type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
updateUser(id: ID!, input: UpdateUserInput!): UpdateUserPayload!
}FastAPI Route Pattern
FastAPI 路由模式
python
from fastapi import APIRouter, Depends, HTTPException, status
router = APIRouter(prefix="/api/v1/users", tags=["users"])
@router.post("", response_model=UserRead, status_code=status.HTTP_201_CREATED)
async def create_user(
user_data: UserCreate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> UserRead:
"""Create a new user in the current tenant."""
repository = UserRepository(db, tenant_id=current_user.tenant_id)
user = await repository.create(user_data)
return userpython
from fastapi import APIRouter, Depends, HTTPException, status
router = APIRouter(prefix="/api/v1/users", tags=["users"])
@router.post("", response_model=UserRead, status_code=status.HTTP_201_CREATED)
async def create_user(
user_data: UserCreate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> UserRead:
"""Create a new user in the current tenant."""
repository = UserRepository(db, tenant_id=current_user.tenant_id)
user = await repository.create(user_data)
return userPydantic Schema Pattern
Pydantic Schema 模式
python
from pydantic import BaseModel, EmailStr, Field, ConfigDict
class UserCreate(BaseModel):
"""Schema for creating a new user."""
email: EmailStr
full_name: str = Field(..., min_length=1, max_length=255)
password: str = Field(..., min_length=8)
class UserRead(BaseModel):
"""Schema for reading user data (public fields only)."""
id: str
tenant_id: str
email: EmailStr
full_name: str
created_at: datetime
model_config = ConfigDict(from_attributes=True)python
from pydantic import BaseModel, EmailStr, Field, ConfigDict
class UserCreate(BaseModel):
"""Schema for creating a new user."""
email: EmailStr
full_name: str = Field(..., min_length=1, max_length=255)
password: str = Field(..., min_length=8)
class UserRead(BaseModel):
"""Schema for reading user data (public fields only)."""
id: str
tenant_id: str
email: EmailStr
full_name: str
created_at: datetime
model_config = ConfigDict(from_attributes=True)Pagination Patterns
分页模式
Cursor-Based (recommended):
GET /posts?limit=20&cursor=eyJpZCI6MTIzfQ
Response:
{
"data": [...],
"pagination": {
"nextCursor": "eyJpZCI6MTQzfQ",
"hasMore": true
}
}Offset-Based (simpler):
GET /posts?limit=20&offset=40
Response:
{
"data": [...],
"pagination": {
"total": 500,
"limit": 20,
"offset": 40
}
}基于游标(推荐):
GET /posts?limit=20&cursor=eyJpZCI6MTIzfQ
Response:
{
"data": [...],
"pagination": {
"nextCursor": "eyJpZCI6MTQzfQ",
"hasMore": true
}
}基于偏移(更简单):
GET /posts?limit=20&offset=40
Response:
{
"data": [...],
"pagination": {
"total": 500,
"limit": 20,
"offset": 40
}
}Authentication Patterns
认证模式
JWT Token Usage:
http
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...API Key Usage:
http
X-API-Key: sk_live_abc123def456OAuth 2.0 Flows:
- Authorization Code Flow - Web apps with backend
- Client Credentials Flow - Service-to-service
- PKCE Flow - Mobile/SPA apps
JWT Token 使用方式:
http
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...API Key 使用方式:
http
X-API-Key: sk_live_abc123def456OAuth 2.0 流程:
- 授权码流程 - 带后端的 Web 应用
- 客户端凭证流程 - 服务间通信
- PKCE 流程 - 移动/SPA 应用
Rate Limiting Headers
速率限制头部
http
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 75
X-RateLimit-Reset: 1698340800
Retry-After: 60http
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 75
X-RateLimit-Reset: 1698340800
Retry-After: 60Available Resources
可用资源
References
参考文档
| File | Description |
|---|---|
| Comprehensive REST API patterns and status codes |
| OAuth 2.0, JWT, API keys, MFA patterns |
| API versioning and deprecation |
| Health checks, webhooks, batch operations |
| GraphQL schema design patterns |
| Apollo Federation architecture |
| GraphQL performance, DataLoader, caching |
| Python library SOLID principles |
| Python PEP quick reference |
| FastAPI main app configuration |
| OpenAPI customization |
| FastAPI exception handlers |
| CORS and rate limiting setup |
| Complete OpenAPI 3.1 example |
| GraphQL with Relay connections |
| Protocol Buffer definitions |
| Tier-based rate limit config |
| Auth, CORS, security headers |
| 文件 | 描述 |
|---|---|
| 全面的 REST API 模式和状态码 |
| OAuth 2.0、JWT、API 密钥、MFA 模式 |
| API 版本控制与弃用策略 |
| 健康检查、Webhook、批量操作 |
| GraphQL schema 设计模式 |
| Apollo Federation 架构 |
| GraphQL 性能优化、DataLoader、缓存 |
| Python 库 SOLID 原则 |
| Python PEP 快速参考 |
| FastAPI 主应用配置 |
| OpenAPI 自定义配置 |
| FastAPI 异常处理器 |
| CORS 和速率限制设置 |
| 完整的 OpenAPI 3.1 示例 |
| 带 Relay 连接的 GraphQL 示例 |
| Protocol Buffer 定义 |
| 基于层级的速率限制配置 |
| 认证、CORS、安全头部 |
Templates
模板
| File | Description |
|---|---|
| Complete CRUD router template |
| Request/response schema template |
| Repository with tenant isolation |
| Upstash Redis rate limiter |
| FastAPI exception handlers |
| TanStack Start server functions |
| 文件 | 描述 |
|---|---|
| 完整的 CRUD 路由模板 |
| 请求/响应 schema 模板 |
| 带租户隔离的仓库模式 |
| Upstash Redis 速率限制器 |
| FastAPI 异常处理器 |
| TanStack Start 服务器函数 |
Examples
示例
| File | Description |
|---|---|
| CRUD endpoints with repository |
| Validation schema examples |
| Pagination implementation |
| API testing patterns |
| TanStack Start examples |
| Blog API OpenAPI specification |
| Full GraphQL schema with subscriptions |
| 文件 | 描述 |
|---|---|
| 带仓库模式的 CRUD 端点 |
| 验证 schema 示例 |
| 分页实现示例 |
| API 测试模式 |
| TanStack Start 示例 |
| 博客 API 的 OpenAPI 规范 |
| 带订阅功能的完整 GraphQL schema |
Scripts
脚本
| File | Description |
|---|---|
| Analyze GraphQL schemas for quality |
| Generate TypeScript resolvers |
| Scaffold Apollo Federation subgraphs |
| OpenAPI validation and docs generation |
| Validate API specifications |
| 文件 | 描述 |
|---|---|
| 分析 GraphQL schema 的质量 |
| 生成 TypeScript 解析器 |
| 快速搭建 Apollo Federation 子图 |
| OpenAPI 验证与文档生成 |
| 验证 API 规范 |
Assets (Python Library)
资源(Python 库)
| File | Description |
|---|---|
| Production-ready pyproject.toml |
| Library README template |
| Contribution guide |
| Recommended package layout |
| Test organization |
| Exception hierarchy pattern |
| Configuration pattern |
| 文件 | 描述 |
|---|---|
| 生产级 pyproject.toml 模板 |
| 库 README 模板 |
| 贡献指南模板 |
| 推荐的包布局 |
| 测试组织方式 |
| 异常层级模式 |
| 配置模式 |
Checklists
检查清单
| File | Description |
|---|---|
| API design review checklist |
| Security review checklist |
| 文件 | 描述 |
|---|---|
| API 设计评审清单 |
| 安全评审清单 |
Core Workflows
核心工作流
1. Design a REST API
1. 设计 REST API
- Identify resources (nouns): Users, Posts, Comments
- Design URL structure with proper nesting
- Choose appropriate HTTP methods
- Define request/response schemas
- Document with OpenAPI specification
- Implement pagination and filtering
- Add authentication and rate limiting
- 识别资源(名词):用户、帖子、评论
- 设计合理嵌套的 URL 结构
- 选择合适的 HTTP 方法
- 定义请求/响应 schema
- 使用 OpenAPI 规范编写文档
- 实现分页与过滤
- 添加认证与速率限制
2. Build a GraphQL API
2. 构建 GraphQL API
- Define schema types with descriptions
- Design queries with pagination (Relay connections)
- Create mutations with input types and payloads
- Implement DataLoader for N+1 prevention
- Add authentication in resolvers
- Configure caching and complexity limits
- 定义带描述的 schema 类型
- 设计带分页的查询(Relay 连接)
- 创建带输入类型和返回 payload 的变更
- 实现 DataLoader 避免 N+1 查询
- 在解析器中添加认证
- 配置缓存与复杂度限制
3. Set Up Apollo Federation
3. 搭建 Apollo Federation
bash
undefinedbash
undefinedScaffold subgraphs
快速搭建子图
python scripts/federation_scaffolder.py users-service --entities User,Profile
python scripts/federation_scaffolder.py posts-service --entities Post --references User
python scripts/federation_scaffolder.py users-service --entities User,Profile
python scripts/federation_scaffolder.py posts-service --entities Post --references User
Configure gateway
配置网关
python scripts/federation_scaffolder.py gateway --subgraphs users:4001,posts:4002
undefinedpython scripts/federation_scaffolder.py gateway --subgraphs users:4001,posts:4002
undefined4. Validate API Specification
4. 验证 API 规范
bash
undefinedbash
undefinedValidate OpenAPI spec
验证 OpenAPI 规范
python scripts/api_helper.py validate --spec openapi.yaml
python scripts/api_helper.py validate --spec openapi.yaml
Analyze GraphQL schema
分析 GraphQL schema
python scripts/schema_analyzer.py schema.graphql --validate
python scripts/schema_analyzer.py schema.graphql --validate
Generate documentation
生成文档
python scripts/api_helper.py docs --spec openapi.yaml --output docs/
undefinedpython scripts/api_helper.py docs --spec openapi.yaml --output docs/
undefinedAnti-Patterns to Avoid
需避免的反模式
- Verb-Based URLs - Use not
/users/getUsers - Inconsistent Response Envelopes - Always use consistent structure
- Breaking Changes Without Versioning - Use semantic versioning
- N+1 Queries in GraphQL - Use DataLoader for batching
- Over-fetching REST Endpoints - Support sparse fieldsets
- Missing Pagination - Always paginate list endpoints
- No Idempotency Keys - Accept header for mutations
Idempotency-Key - Leaky Internal Errors - Generic messages in production
- Missing CORS Configuration - Configure allowed origins explicitly
- No Rate Limiting - Implement per-user/per-endpoint limits
- 基于动词的 URL - 使用 而非
/users/getUsers - 不一致的响应结构 - 始终使用统一的响应格式
- 无版本控制的破坏性变更 - 使用语义化版本控制
- GraphQL 中的 N+1 查询 - 使用 DataLoader 进行批量处理
- REST 端点过度获取 - 支持稀疏字段集
- 缺少分页 - 所有列表端点都需实现分页
- 无幂等密钥 - 为变更操作接受 头部
Idempotency-Key - 暴露内部错误 - 生产环境使用通用错误信息
- 缺少 CORS 配置 - 显式配置允许的源
- 无速率限制 - 实现按用户/端点的限制
Quality Checklist
质量检查清单
[ ] All endpoints use nouns, not verbs
[ ] Consistent response envelope structure
[ ] Error responses include codes and actionable messages
[ ] Pagination on all list endpoints
[ ] Authentication/authorization documented
[ ] Rate limit headers defined
[ ] Versioning strategy documented
[ ] CORS configured for known origins
[ ] Idempotency keys for mutating operations
[ ] OpenAPI spec validates without errors
[ ] SDK generation tested
[ ] Examples for all request/response types[ ] 所有端点使用名词而非动词
[ ] 统一的响应结构
[ ] 错误响应包含错误码和可操作信息
[ ] 所有列表端点实现分页
[ ] 认证/授权已文档化
[ ] 定义了速率限制头部
[ ] 版本控制策略已文档化
[ ] 为已知源配置了 CORS
[ ] 变更操作支持幂等密钥
[ ] OpenAPI 规范验证通过
[ ] SDK 生成已测试
[ ] 所有请求/响应类型都有示例When to Use This Skill
使用场景
- Creating new API endpoints (REST, GraphQL, gRPC)
- Designing resource hierarchies and schemas
- Writing OpenAPI/Swagger specifications
- Implementing authentication and authorization
- Setting up pagination, filtering, and sorting
- Configuring rate limiting and CORS
- Designing Python library APIs
- Reviewing API designs in pull requests
- 创建新的 API 端点(REST、GraphQL、gRPC)
- 设计资源层级与 schema
- 编写 OpenAPI/Swagger 规范
- 实现认证与授权
- 配置分页、过滤与排序
- 设置速率限制与 CORS
- 设计 Python 库 API
- 评审拉取请求中的 API 设计
Source Skills
源技能
This merged skill combines content from the following legacy skills (now part of ):
api-design- FastAPI, Pydantic, multi-tenant patterns
- Library structure, SOLID principles, PEP standards
- GraphQL, Apollo, Federation, DataLoader
- REST, gRPC, security, versioning
- Documentation, authentication, best practices
Version: 1.0.0
Last Updated: 2025-01-18
本合并技能整合了以下旧技能的内容(现已归入 ):
api-design- FastAPI、Pydantic、多租户模式
- 库结构、SOLID 原则、PEP 标准
- GraphQL、Apollo、Federation、DataLoader
- REST、gRPC、安全、版本控制
- 文档、认证、最佳实践
版本: 1.0.0
最后更新: 2025-01-18