tech-api-integration
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseREST 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方法
| Method | Purpose | Idempotent? | Example |
|---|---|---|---|
| GET | Read data | Yes | |
| POST | Create new resource | No | |
| PUT | Replace entire resource | Yes | |
| PATCH | Update partial resource | Yes | |
| DELETE | Remove resource | Yes | |
| 方法 | 用途 | 幂等性? | 示例 |
|---|---|---|---|
| GET | 读取数据 | 是 | |
| POST | 创建新资源 | 否 | |
| PUT | 替换完整资源 | 是 | |
| PATCH | 更新部分资源 | 是 | |
| DELETE | 删除资源 | 是 | |
Status Codes
状态码
| Range | Meaning | Common Codes |
|---|---|---|
| 2xx | Success | 200 OK, 201 Created, 204 No Content |
| 3xx | Redirect | 301 Moved, 304 Not Modified |
| 4xx | Client error (your fault) | 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many Requests |
| 5xx | Server 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
身份验证类型
| Type | How It Works | When Used |
|---|---|---|
| API Key | Key in header or query param | Simple APIs, server-to-server |
| Bearer Token | | OAuth 2.0, JWT-based APIs |
| OAuth 2.0 | Token exchange flow (authorize → token → API call) | User-delegated access (Google, FB) |
| Basic Auth | Base64(username:password) in header | Legacy, internal APIs |
| HMAC Signature | Sign request with secret key | Payment gateways, high-security |
| 类型 | 工作原理 | 适用场景 |
|---|---|---|
| API Key | 在请求头或查询参数中携带密钥 | 简单API、服务器到服务器场景 |
| 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
速率限制处理
| Strategy | How |
|---|---|
Respect | Wait the specified seconds before retrying |
| Exponential backoff | Wait 1s, 2s, 4s, 8s between retries |
| Token bucket | Track request count, pause when approaching limit |
| Queue requests | Use a job queue (Celery, Bull) for high-volume integrations |
| 策略 | 实现方式 |
|---|---|
遵循 | 在重试前等待指定的秒数 |
| 指数退避 | 重试间隔依次为1秒、2秒、4秒、8秒 |
| 令牌桶算法 | 跟踪请求次数,接近限制时暂停 |
| 请求队列 | 在高流量集成场景中使用任务队列(如Celery、Bull) |
Integration Checklist
集成检查清单
- Read API documentation completely
- Test auth flow (get valid token/key)
- Test each endpoint with curl/Postman first
- Implement error handling for all status code ranges
- Implement rate limit handling
- Implement retry logic with backoff
- Log all requests and responses (redact secrets)
- Handle API versioning (pin to specific version)
- Set timeouts (connect: 5s, read: 30s)
- Monitor for API deprecation notices
- 完整阅读API文档
- 测试身份验证流程(获取有效的令牌/密钥)
- 先使用curl/Postman测试每个端点
- 为所有状态码范围实现错误处理
- 实现速率限制处理逻辑
- 实现带退避机制的重试逻辑
- 记录所有请求和响应(脱敏敏感信息)
- 处理API版本控制(固定到特定版本)
- 设置超时时间(连接超时:5秒,读取超时:30秒)
- 监控API弃用通知
Output Format
输出格式
markdown
undefinedmarkdown
undefinedAPI 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
使用的端点
| Endpoint | Method | Purpose | Auth |
|---|---|---|---|
| {path} | GET/POST | {what it does} | {auth type} |
| 端点 | 方法 | 用途 | 身份验证方式 |
|---|---|---|---|
| {path} | GET/POST | {功能描述} | {身份验证类型} |
Error Handling
错误处理方案
| Error | Response | Our Action |
|---|---|---|
| 401 | Unauthorized | Refresh token, retry |
| 429 | Rate limited | Backoff, retry after Retry-After |
| 500 | Server error | Retry 3x with exponential backoff |
| 错误类型 | 响应信息 | 我方处理动作 |
|---|---|---|
| 401 | 未授权 | 刷新令牌后重试 |
| 429 | 速率限制触发 | 退避等待,遵循Retry-After头后重试 |
| 500 | 服务端错误 | 最多3次指数退避重试 |
Implementation Timeline
实施时间线
| Phase | Task | Duration |
|---|---|---|
| 1 | Auth + basic call | {days} |
| 2 | Full integration | {days} |
| 3 | Error handling + monitoring | {days} |
undefined| 阶段 | 任务 | 时长 |
|---|---|---|
| 1 | 身份验证 + 基础调用 | {天数} |
| 2 | 完整集成开发 | {天数} |
| 3 | 错误处理 + 监控 | {天数} |
undefinedGotchas
注意事项
- 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 token or
next_pageparameter.offset - 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