api-design

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API 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:
  • /api/v1/users
    (plural nouns, lowercase with hyphens)
  • /api/v1/organizations/{org_id}/teams
    (hierarchical, max 2 levels)
  • Never use verbs:
    /getUsers
    or underscores:
    /user_profiles
HTTP Methods:
  • GET
    - Retrieve resources (safe, idempotent, cacheable)
  • POST
    - Create new resources (returns 201 with Location header)
  • PUT
    - Replace entire resource (idempotent)
  • PATCH
    - Partial update (only changed fields)
  • DELETE
    - Remove resource (idempotent, returns 204)
URL 模式:
  • /api/v1/users
    (复数名词,小写连字符格式)
  • /api/v1/organizations/{org_id}/teams
    (层级结构,最多 2 级)
  • 禁止使用动词:
    /getUsers
    或下划线:
    /user_profiles
HTTP 方法:
  • GET
    - 获取资源(安全、幂等、可缓存)
  • POST
    - 创建新资源(返回 201 状态码及 Location 头部)
  • PUT
    - 替换整个资源(幂等)
  • PATCH
    - 部分更新(仅修改指定字段)
  • DELETE
    - 删除资源(幂等,返回 204 状态码)

HTTP Status Codes

HTTP 状态码

Success:
  • 200 OK
    - GET, PUT, PATCH success
  • 201 Created
    - POST success (include Location header)
  • 204 No Content
    - DELETE success
Client Errors:
  • 400 Bad Request
    - Malformed request
  • 401 Unauthorized
    - Missing/invalid authentication
  • 403 Forbidden
    - Insufficient permissions
  • 404 Not Found
    - Resource doesn't exist
  • 409 Conflict
    - Duplicate resource
  • 422 Unprocessable Entity
    - Validation errors
  • 429 Too Many Requests
    - Rate limit exceeded
Server Errors:
  • 500 Internal Server Error
    - Unhandled exception
  • 503 Service Unavailable
    - Database/service down
成功:
  • 200 OK
    - GET、PUT、PATCH 请求成功
  • 201 Created
    - POST 请求成功(需包含 Location 头部)
  • 204 No Content
    - DELETE 请求成功
客户端错误:
  • 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 user
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 user

Pydantic 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_abc123def456
OAuth 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_abc123def456
OAuth 2.0 流程:
  • 授权码流程 - 带后端的 Web 应用
  • 客户端凭证流程 - 服务间通信
  • PKCE 流程 - 移动/SPA 应用

Rate Limiting Headers

速率限制头部

http
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 75
X-RateLimit-Reset: 1698340800
Retry-After: 60
http
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 75
X-RateLimit-Reset: 1698340800
Retry-After: 60

Available Resources

可用资源

References

参考文档

FileDescription
references/rest-best-practices.md
Comprehensive REST API patterns and status codes
references/authentication.md
OAuth 2.0, JWT, API keys, MFA patterns
references/versioning-strategies.md
API versioning and deprecation
references/common-patterns.md
Health checks, webhooks, batch operations
references/schema-patterns.md
GraphQL schema design patterns
references/federation-guide.md
Apollo Federation architecture
references/performance-optimization.md
GraphQL performance, DataLoader, caching
references/architectural-principles.md
Python library SOLID principles
references/pep-standards.md
Python PEP quick reference
references/fastapi-setup.md
FastAPI main app configuration
references/openapi.md
OpenAPI customization
references/error-handlers.md
FastAPI exception handlers
references/cors-rate-limiting.md
CORS and rate limiting setup
references/openapi-spec.yaml
Complete OpenAPI 3.1 example
references/graphql-schema.graphql
GraphQL with Relay connections
references/grpc-service.proto
Protocol Buffer definitions
references/rate-limiting.yaml
Tier-based rate limit config
references/api-security.yaml
Auth, CORS, security headers
文件描述
references/rest-best-practices.md
全面的 REST API 模式和状态码
references/authentication.md
OAuth 2.0、JWT、API 密钥、MFA 模式
references/versioning-strategies.md
API 版本控制与弃用策略
references/common-patterns.md
健康检查、Webhook、批量操作
references/schema-patterns.md
GraphQL schema 设计模式
references/federation-guide.md
Apollo Federation 架构
references/performance-optimization.md
GraphQL 性能优化、DataLoader、缓存
references/architectural-principles.md
Python 库 SOLID 原则
references/pep-standards.md
Python PEP 快速参考
references/fastapi-setup.md
FastAPI 主应用配置
references/openapi.md
OpenAPI 自定义配置
references/error-handlers.md
FastAPI 异常处理器
references/cors-rate-limiting.md
CORS 和速率限制设置
references/openapi-spec.yaml
完整的 OpenAPI 3.1 示例
references/graphql-schema.graphql
带 Relay 连接的 GraphQL 示例
references/grpc-service.proto
Protocol Buffer 定义
references/rate-limiting.yaml
基于层级的速率限制配置
references/api-security.yaml
认证、CORS、安全头部

Templates

模板

FileDescription
templates/fastapi-crud-endpoint.py
Complete CRUD router template
templates/pydantic-schemas.py
Request/response schema template
templates/repository-pattern.py
Repository with tenant isolation
templates/rate-limiter.py
Upstash Redis rate limiter
templates/error-handler.py
FastAPI exception handlers
templates/tanstack-server-function.ts
TanStack Start server functions
文件描述
templates/fastapi-crud-endpoint.py
完整的 CRUD 路由模板
templates/pydantic-schemas.py
请求/响应 schema 模板
templates/repository-pattern.py
带租户隔离的仓库模式
templates/rate-limiter.py
Upstash Redis 速率限制器
templates/error-handler.py
FastAPI 异常处理器
templates/tanstack-server-function.ts
TanStack Start 服务器函数

Examples

示例

FileDescription
examples/fastapi-crud.md
CRUD endpoints with repository
examples/pydantic-schemas.md
Validation schema examples
examples/pagination.md
Pagination implementation
examples/testing.md
API testing patterns
examples/tanstack-start.md
TanStack Start examples
examples/openapi-spec.yaml
Blog API OpenAPI specification
examples/graphql-schema.graphql
Full GraphQL schema with subscriptions
文件描述
examples/fastapi-crud.md
带仓库模式的 CRUD 端点
examples/pydantic-schemas.md
验证 schema 示例
examples/pagination.md
分页实现示例
examples/testing.md
API 测试模式
examples/tanstack-start.md
TanStack Start 示例
examples/openapi-spec.yaml
博客 API 的 OpenAPI 规范
examples/graphql-schema.graphql
带订阅功能的完整 GraphQL schema

Scripts

脚本

FileDescription
scripts/schema_analyzer.py
Analyze GraphQL schemas for quality
scripts/resolver_generator.py
Generate TypeScript resolvers
scripts/federation_scaffolder.py
Scaffold Apollo Federation subgraphs
scripts/api_helper.py
OpenAPI validation and docs generation
scripts/validate-api-spec.sh
Validate API specifications
文件描述
scripts/schema_analyzer.py
分析 GraphQL schema 的质量
scripts/resolver_generator.py
生成 TypeScript 解析器
scripts/federation_scaffolder.py
快速搭建 Apollo Federation 子图
scripts/api_helper.py
OpenAPI 验证与文档生成
scripts/validate-api-spec.sh
验证 API 规范

Assets (Python Library)

资源(Python 库)

FileDescription
assets/pyproject.toml.template
Production-ready pyproject.toml
assets/README.md.template
Library README template
assets/CONTRIBUTING.md.template
Contribution guide
assets/project-structure.txt
Recommended package layout
assets/test-structure.txt
Test organization
assets/example-exceptions.py
Exception hierarchy pattern
assets/example-config.py
Configuration pattern
文件描述
assets/pyproject.toml.template
生产级 pyproject.toml 模板
assets/README.md.template
库 README 模板
assets/CONTRIBUTING.md.template
贡献指南模板
assets/project-structure.txt
推荐的包布局
assets/test-structure.txt
测试组织方式
assets/example-exceptions.py
异常层级模式
assets/example-config.py
配置模式

Checklists

检查清单

FileDescription
checklists/api-design-checklist.md
API design review checklist
checklists/security-review.md
Security review checklist
文件描述
checklists/api-design-checklist.md
API 设计评审清单
checklists/security-review.md
安全评审清单

Core Workflows

核心工作流

1. Design a REST API

1. 设计 REST API

  1. Identify resources (nouns): Users, Posts, Comments
  2. Design URL structure with proper nesting
  3. Choose appropriate HTTP methods
  4. Define request/response schemas
  5. Document with OpenAPI specification
  6. Implement pagination and filtering
  7. Add authentication and rate limiting
  1. 识别资源(名词):用户、帖子、评论
  2. 设计合理嵌套的 URL 结构
  3. 选择合适的 HTTP 方法
  4. 定义请求/响应 schema
  5. 使用 OpenAPI 规范编写文档
  6. 实现分页与过滤
  7. 添加认证与速率限制

2. Build a GraphQL API

2. 构建 GraphQL API

  1. Define schema types with descriptions
  2. Design queries with pagination (Relay connections)
  3. Create mutations with input types and payloads
  4. Implement DataLoader for N+1 prevention
  5. Add authentication in resolvers
  6. Configure caching and complexity limits
  1. 定义带描述的 schema 类型
  2. 设计带分页的查询(Relay 连接)
  3. 创建带输入类型和返回 payload 的变更
  4. 实现 DataLoader 避免 N+1 查询
  5. 在解析器中添加认证
  6. 配置缓存与复杂度限制

3. Set Up Apollo Federation

3. 搭建 Apollo Federation

bash
undefined
bash
undefined

Scaffold 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
undefined
python scripts/federation_scaffolder.py gateway --subgraphs users:4001,posts:4002
undefined

4. Validate API Specification

4. 验证 API 规范

bash
undefined
bash
undefined

Validate 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/
undefined
python scripts/api_helper.py docs --spec openapi.yaml --output docs/
undefined

Anti-Patterns to Avoid

需避免的反模式

  1. Verb-Based URLs - Use
    /users
    not
    /getUsers
  2. Inconsistent Response Envelopes - Always use consistent structure
  3. Breaking Changes Without Versioning - Use semantic versioning
  4. N+1 Queries in GraphQL - Use DataLoader for batching
  5. Over-fetching REST Endpoints - Support sparse fieldsets
  6. Missing Pagination - Always paginate list endpoints
  7. No Idempotency Keys - Accept
    Idempotency-Key
    header for mutations
  8. Leaky Internal Errors - Generic messages in production
  9. Missing CORS Configuration - Configure allowed origins explicitly
  10. No Rate Limiting - Implement per-user/per-endpoint limits
  1. 基于动词的 URL - 使用
    /users
    而非
    /getUsers
  2. 不一致的响应结构 - 始终使用统一的响应格式
  3. 无版本控制的破坏性变更 - 使用语义化版本控制
  4. GraphQL 中的 N+1 查询 - 使用 DataLoader 进行批量处理
  5. REST 端点过度获取 - 支持稀疏字段集
  6. 缺少分页 - 所有列表端点都需实现分页
  7. 无幂等密钥 - 为变更操作接受
    Idempotency-Key
    头部
  8. 暴露内部错误 - 生产环境使用通用错误信息
  9. 缺少 CORS 配置 - 显式配置允许的源
  10. 无速率限制 - 实现按用户/端点的限制

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