[ PROMPT_NODE_23662 ]
API Integration Specialist
[ SKILL_DOCUMENTATION ]
# API 集成专家
为将外部 API 集成到应用程序中提供专家指导,涵盖生产级模式、安全最佳实践和全面的错误处理。
## 何时使用此技能
在以下场景使用此技能:
- 集成第三方 API (Stripe, Twilio, SendGrid 等)
- 构建 API 客户端库或包装器
- 实现 OAuth 2.0、API 密钥或 JWT 身份验证
- 设置 Webhook 和事件驱动的集成
- 处理速率限制、重试和熔断器
- 转换 API 响应以供应用程序使用
- 调试 API 集成问题
## 核心集成原则
### 1. 身份验证与安全
**API 密钥管理:**
javascript
// 将密钥存储在环境变量中,切勿硬编码
const apiClient = new APIClient({
apiKey: process.env.SERVICE_API_KEY,
baseURL: process.env.SERVICE_BASE_URL
});
**OAuth 2.0 流程:**
javascript
// 授权码模式
const oauth = new OAuth2Client({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
redirectUri: process.env.REDIRECT_URI,
scopes: ['read:users', 'write:data']
});
// 获取授权 URL
const authUrl = oauth.getAuthorizationUrl();
// 使用 code 换取令牌
const tokens = await oauth.exchangeCode(code);
### 2. 请求/响应处理
**标准化请求结构:**
javascript
async function makeRequest(endpoint, options = {}) {
const defaultHeaders = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
'User-Agent': 'MyApp/1.0.0'
};
const response = await fetch(`${baseURL}${endpoint}`, {
...options,
headers: { ...defaultHeaders, ...options.headers }
});
if (!response.ok) {
throw new APIError(response.status, await response.json());
}
return response.json();
}
**响应转换:**
javascript
class APIClient {
async getUser(userId) {
const raw = await this.request(`/users/${userId}`);
// 将外部 API 格式转换为内部模型
return {
id: raw.user_id,
email: raw.email_address,
name: `${raw.first_name} ${raw.last_name}`,
createdAt: new Date(raw.created_timestamp)
};
}
}
### 3. 错误处理
**结构化错误类型:**
javascript
class APIError extends Error {
constructor(status, body) {
super(`API Error: ${status}`);
this.status = status;
this.body = body;
this.isAPIError = true;
}
isRateLimited() {
return this.status === 429;