tech-api-integration

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

REST API Integration Guide

REST API集成指南

Framework

核心框架

IRON LAW: Read the Docs, Then Build, Then Handle Errors

1. Read the API documentation completely (auth, endpoints, rate limits, errors)
2. Get a successful request working in isolation (curl/Postman)
3. Build error handling BEFORE building features

Skipping step 1 wastes hours on trial-and-error. Skipping step 3
creates fragile integrations that break silently in production.
IRON LAW: Read the Docs, Then Build, Then Handle Errors

1. Read the API documentation completely (auth, endpoints, rate limits, errors)
2. Get a successful request working in isolation (curl/Postman)
3. Build error handling BEFORE building features

Skipping step 1 wastes hours on trial-and-error. Skipping step 3
creates fragile integrations that break silently in production.

HTTP Methods

HTTP方法

MethodPurposeIdempotent?Example
GETRead dataYes
GET /users/123
POSTCreate new resourceNo
POST /users
+ body
PUTReplace entire resourceYes
PUT /users/123
+ full body
PATCHUpdate partial resourceYes
PATCH /users/123
+ partial body
DELETERemove resourceYes
DELETE /users/123
方法用途幂等性?示例
GET读取数据
GET /users/123
POST创建新资源
POST /users
+ 请求体
PUT替换完整资源
PUT /users/123
+ 完整请求体
PATCH更新部分资源
PATCH /users/123
+ 部分请求体
DELETE删除资源
DELETE /users/123

Status Codes

状态码

RangeMeaningCommon Codes
2xxSuccess200 OK, 201 Created, 204 No Content
3xxRedirect301 Moved, 304 Not Modified
4xxClient error (your fault)400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many Requests
5xxServer error (their fault)500 Internal, 502 Bad Gateway, 503 Service Unavailable
状态码范围含义常见状态码
2xx成功200 OK, 201 Created, 204 No Content
3xx重定向301 Moved, 304 Not Modified
4xx客户端错误(由你方导致)400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many Requests
5xx服务端错误(由对方导致)500 Internal, 502 Bad Gateway, 503 Service Unavailable

Authentication Types

身份验证类型

TypeHow It WorksWhen Used
API KeyKey in header or query paramSimple APIs, server-to-server
Bearer Token
Authorization: Bearer <token>
OAuth 2.0, JWT-based APIs
OAuth 2.0Token exchange flow (authorize → token → API call)User-delegated access (Google, FB)
Basic AuthBase64(username:password) in headerLegacy, internal APIs
HMAC SignatureSign request with secret keyPayment gateways, high-security
类型工作原理适用场景
API Key在请求头或查询参数中携带密钥简单API、服务器到服务器场景
Bearer Token
Authorization: Bearer <token>
OAuth 2.0、基于JWT的API
OAuth 2.0令牌交换流程(授权→获取令牌→调用API)用户委托访问(如谷歌、脸书)
Basic Auth在请求头中携带Base64编码的“用户名:密码”遗留系统、内部API
HMAC Signature使用密钥对请求进行签名支付网关、高安全性场景

Error Handling Strategy

错误处理策略

try:
    response = api.call(request)
    if response.status == 429:  # Rate limited
        wait(response.headers['Retry-After'])
        retry()
    elif response.status >= 500:  # Server error
        retry_with_backoff(max_retries=3)
    elif response.status >= 400:  # Client error
        log_error(response.body)
        raise ClientError(response.body['message'])
    else:
        return response.json()
try:
    response = api.call(request)
    if response.status == 429:  # 速率限制
        wait(response.headers['Retry-After'])
        retry()
    elif response.status >= 500:  # 服务端错误
        retry_with_backoff(max_retries=3)
    elif response.status >= 400:  # 客户端错误
        log_error(response.body)
        raise ClientError(response.body['message'])
    else:
        return response.json()

Rate Limiting

速率限制处理

StrategyHow
Respect
Retry-After
header
Wait the specified seconds before retrying
Exponential backoffWait 1s, 2s, 4s, 8s between retries
Token bucketTrack request count, pause when approaching limit
Queue requestsUse a job queue (Celery, Bull) for high-volume integrations
策略实现方式
遵循
Retry-After
请求头
在重试前等待指定的秒数
指数退避重试间隔依次为1秒、2秒、4秒、8秒
令牌桶算法跟踪请求次数,接近限制时暂停
请求队列在高流量集成场景中使用任务队列(如Celery、Bull)

Integration Checklist

集成检查清单

  1. Read API documentation completely
  2. Test auth flow (get valid token/key)
  3. Test each endpoint with curl/Postman first
  4. Implement error handling for all status code ranges
  5. Implement rate limit handling
  6. Implement retry logic with backoff
  7. Log all requests and responses (redact secrets)
  8. Handle API versioning (pin to specific version)
  9. Set timeouts (connect: 5s, read: 30s)
  10. Monitor for API deprecation notices
  1. 完整阅读API文档
  2. 测试身份验证流程(获取有效的令牌/密钥)
  3. 先使用curl/Postman测试每个端点
  4. 为所有状态码范围实现错误处理
  5. 实现速率限制处理逻辑
  6. 实现带退避机制的重试逻辑
  7. 记录所有请求和响应(脱敏敏感信息)
  8. 处理API版本控制(固定到特定版本)
  9. 设置超时时间(连接超时:5秒,读取超时:30秒)
  10. 监控API弃用通知

Output Format

输出格式

markdown
undefined
markdown
undefined

API Integration Plan: {API Name}

API集成方案:{API名称}

API Overview

API概述

  • Base URL: {url}
  • Auth: {type}
  • Rate limit: {N requests/period}
  • Documentation: {link}
  • 基础URL:{url}
  • 身份验证方式:{type}
  • 速率限制:{N}次请求/{周期}
  • 文档链接:{link}

Endpoints Used

使用的端点

EndpointMethodPurposeAuth
{path}GET/POST{what it does}{auth type}
端点方法用途身份验证方式
{path}GET/POST{功能描述}{身份验证类型}

Error Handling

错误处理方案

ErrorResponseOur Action
401UnauthorizedRefresh token, retry
429Rate limitedBackoff, retry after Retry-After
500Server errorRetry 3x with exponential backoff
错误类型响应信息我方处理动作
401未授权刷新令牌后重试
429速率限制触发退避等待,遵循Retry-After头后重试
500服务端错误最多3次指数退避重试

Implementation Timeline

实施时间线

PhaseTaskDuration
1Auth + basic call{days}
2Full integration{days}
3Error handling + monitoring{days}
undefined
阶段任务时长
1身份验证 + 基础调用{天数}
2完整集成开发{天数}
3错误处理 + 监控{天数}
undefined

Gotchas

注意事项

  • Sandbox vs production: Most APIs have a sandbox/test environment. Build and test there first. Production API keys should never be in code.
  • Pagination: APIs return paginated results. Handle all pages, not just the first. Check for
    next_page
    token or
    offset
    parameter.
  • Webhook reliability: If using webhooks, implement idempotent handlers (same event received twice should not duplicate data). Store event IDs to deduplicate.
  • API changes break things: Pin to a specific API version. Subscribe to the provider's changelog/deprecation notices.
  • Secrets management: API keys and tokens NEVER in source code. Use environment variables or a secrets manager (AWS Secrets Manager, HashiCorp Vault).
  • 沙箱环境vs生产环境:大多数API都提供沙箱/测试环境。先在此环境中开发和测试。生产环境API密钥绝不能硬编码到代码中。
  • 分页处理:API返回分页结果。需处理所有页面,而非仅第一页。检查
    next_page
    令牌或
    offset
    参数。
  • Webhook可靠性:如果使用Webhook,需实现幂等处理器(同一事件多次接收不应导致数据重复)。存储事件ID以实现去重。
  • API变更影响:固定使用特定的API版本。订阅服务商的更新日志/弃用通知。
  • 敏感信息管理:API密钥和令牌绝不能出现在源代码中。使用环境变量或敏感信息管理器(如AWS Secrets Manager、HashiCorp Vault)。

References

参考资料

  • For OAuth 2.0 flow details, see
    references/oauth-guide.md
  • For webhook implementation patterns, see
    references/webhook-patterns.md
  • 关于OAuth 2.0流程的详细信息,请参阅
    references/oauth-guide.md
  • 关于Webhook实现模式的信息,请参阅
    references/webhook-patterns.md