api-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API Integration Patterns

API集成模式

Pick the protocol by data shape, ownership, and runtime constraints. Avoid mixing patterns without a clear boundary.
根据数据形态、归属权和运行时约束选择协议。避免在无清晰边界的情况下混合使用模式。

Selection Guide

选型指南

  • REST:
  • Standard CRUD, broad client compatibility, simple caching.
  • GraphQL:
  • Flexible read models, multi-client data composition, schema governance.
  • WebSocket:
  • Bi-directional real-time channels with low-latency updates.
  • SSE:
  • Server-to-client streaming where client push is unnecessary.
  • tRPC:
  • End-to-end TypeScript contracts in monorepos.
  • REST:
  • 标准CRUD操作、广泛的客户端兼容性、简单缓存机制。
  • GraphQL:
  • 灵活的读取模型、多客户端数据组合、Schema治理。
  • WebSocket:
  • 低延迟更新的双向实时通道。
  • SSE:
  • 无需客户端推送的服务器到客户端流传输。
  • tRPC:
  • 单体仓库中的端到端TypeScript契约。

Use This Skill When

适用场景

  • You need to define or refactor API boundaries.
  • Frontend/server data fetching strategy is unclear.
  • Real-time transport choice is blocking implementation.
  • 你需要定义或重构API边界时。
  • 前端/服务器数据获取策略不明确时。
  • 实时传输选择阻碍了实现进度时。

Implementation Workflow

实施流程

1) Define API Contract

1) 定义API契约

  • Identify resource ownership and versioning strategy.
  • Define request/response shapes and error model.
  • Standardize auth, pagination, filtering, and idempotency.
  • 确定资源归属和版本控制策略。
  • 定义请求/响应结构和错误模型。
  • 标准化认证、分页、过滤和幂等性。

2) Choose Transport

2) 选择传输协议

  • REST for core CRUD.
  • GraphQL for query composition.
  • WebSocket/SSE for live updates.
  • tRPC when shared TS types are required and service boundary allows it.
  • REST用于核心CRUD操作。
  • GraphQL用于查询组合。
  • WebSocket/SSE用于实时更新。
  • 当需要共享TS类型且服务边界允许时,使用tRPC。

3) Standardize Client Layer

3) 标准化客户端层

  • Central client factory and interceptors.
  • Typed API wrappers.
  • Uniform retries/timeouts and auth refresh logic.
  • Cache and invalidation rules documented per endpoint group.
  • 集中式客户端工厂和拦截器。
  • 类型化API包装器。
  • 统一的重试/超时和认证刷新逻辑。
  • 按端点组记录缓存和失效规则。

4) Error and Observability

4) 错误处理与可观测性

  • Consistent API error envelope.
  • Correlation IDs and request tracing.
  • Log validation and transport failures separately.
  • 一致的API错误封装。
  • 关联ID和请求追踪。
  • 分别记录验证和传输失败日志。

5) Security Baseline

5) 安全基线

  • Validate input schema at API boundary.
  • Enforce authz at resource/action level.
  • Apply rate limiting and payload size limits.
  • 在API边界验证输入Schema。
  • 在资源/操作层面强制执行授权。
  • 应用速率限制和负载大小限制。

Output Requirements for Agent

Agent输出要求

  • Recommended transport and why.
  • Endpoint/schema proposal.
  • Client integration pattern.
  • Real-time model if needed.
  • Security and testing checklist.
  • 推荐的传输协议及原因。
  • 端点/Schema提案。
  • 客户端集成模式。
  • 如需实时功能,提供实时模型。
  • 安全与测试检查清单。

References

参考资料

  • Full templates for REST, GraphQL, WebSocket, SSE, and tRPC:
    references/guide.md
  • REST、GraphQL、WebSocket、SSE和tRPC的完整模板:
    references/guide.md