关于 API Integration Specialist
为在应用和客户端库中集成外部 API 的开发者提供实践指南,涵盖认证、请求处理、可靠性、安全、Webhook 和故障排查。
主要功能
- 01API 认证与密钥管理
- 02请求和响应转换
- 03结构化错误与重试模式
- 04速率限制与分页
- 05Webhook 签名验证
适用场景
- 01构建第三方 API 客户端
- 02添加 OAuth 或 API 密钥认证
- 03处理速率限制和暂时性故障
- 04验证传入的 Webhook 请求
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ davila7/ claude-code-templates --skill api-integration-specialist安装后在 Claude Code 中输入/api-integration-specialist确认已加载。
详细介绍
API 集成专家
提供将外部 API 集成到应用中的专业指导,涵盖生产级模式、安全最佳实践和全面的错误处理。
何时使用此技能
在以下情况下使用此技能:
- 集成第三方 API(Stripe、Twilio、SendGrid 等)
- 构建 API 客户端库或封装
- 实现 OAuth 2.0、API 密钥或 JWT 身份验证
- 设置 Webhook 和事件驱动集成
- 处理速率限制、重试和熔断器
- 转换 API 响应以供应用使用
- 调试 API 集成问题
核心集成原则
1. 身份验证与安全
API 密钥管理:
// Store keys in environment variables, never in code
const apiClient = new APIClient({
apiKey: process.env.SERVICE_API_KEY,
baseURL: process.env.SERVICE_BASE_URL
});
OAuth 2.0 流程:
// Authorization Code Flow
const oauth = new OAuth2Client({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
redirectUri: process.env.REDIRECT_URI,
scopes: ['read:users', 'write:data']
});
// Get authorization URL
const authUrl = oauth.getAuthorizationUrl();
// Exchange code for tokens
const tokens = await oauth.exchangeCode(code);
2. 请求/响应处理
标准化请求结构:
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();
}
响应转换:
class APIClient {
async getUser(userId) {
const raw = await this.request(`/users/${userId}`);
// Transform external API format to internal model
return {
id: raw.user_id,
email: raw.email_address,
name: `${raw.first_name} ${raw.last_name}`,
createdAt: new Date(raw.created_timestamp)
};
}
}
3. 错误处理
结构化错误类型:
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;
}
isUnauthorized() {
return this.status === 401;
}
isServerError() {
return this.status >= 500;
}
}
带指数退避的重试逻辑:
async function retryWithBackoff(fn, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (error) {
if (!error.isAPIError || !error.isServerError()) {
throw error; // Don't retry client errors
}
if (i === maxRetries - 1) throw error;
const delay = Math.pow(2, i) * 1000; // 1s, 2s, 4s
await sleep(delay);
}
}
}
4. 速率限制
客户端速率限制器:
class RateLimiter {
constructor(maxRequests, windowMs) {
this.maxRequests = maxRequests;
this.windowMs = windowMs;
this.requests = [];
}
async acquire() {
const now = Date.now();
this.requests = this.requests.filter(t => now - t < this.windowMs);
if (this.requests.length >= this.maxRequests) {
const oldestRequest = this.requests[0];
const waitTime = this.windowMs - (now - oldestRequest);
await sleep(waitTime);
return this.acquire();
}
this.requests.push(now);
}
}
const limiter = new RateLimiter(100, 60000); // 100 requests per minute
async function rateLimitedRequest(endpoint, options) {
await limiter.acquire();
return makeRequest(endpoint, options);
}
5. Webhook 处理
Webhook 验证:
function verifyWebhookSignature(payload, signature, secret) {
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expectedSignature)
);
}
app.post('/webhooks/stripe', express.raw({ type: 'application/json' }), (req, res) => {
const signature = req.headers['stripe-signature'];
if (!verifyWebhookSignature(req.body, signature, process.env.STRIPE_WEBHOOK_SECRET)) {
return res.status(401).send('Invalid signature');
}
const event = JSON.parse(req.body);
handleWebhookEvent(event);
res.status(200).send('Received');
});
集成模式
REST API 客户端模式
class ServiceAPIClient {
constructor(config) {
this.apiKey = config.apiKey;
this.baseURL = config.baseURL;
this.timeout = config.timeout || 30000;
}
async request(method, endpoint, data = null) {
const options = {
method,
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
timeout: this.timeout
};
if (data) {
options.body = JSON.stringify(data);
}
const response = await retryWithBackoff(() =>
fetch(`${this.baseURL}${endpoint}`, options)
);
return response.json();
}
// Resource methods
async getResource(id) {
return this.request('GET', `/resources/${id}`);
}
async createResource(data) {
return this.request('POST', '/resources', data);
}
async updateResource(id, data) {
return this.request('PUT', `/resources/${id}`, data);
}
async deleteResource(id) {
return this.request('DELETE', `/resources/${id}`);
}
}
分页处理
async function* fetchAllPages(endpoint, pageSize = 100) {
let cursor = null;
do {
const params = new URLSearchParams({
limit: pageSize,
...(cursor && { cursor })
});
const response = await apiClient.request('GET', `${endpoint}?${params}`);
yield response.data;
cursor = response.pagination?.next_cursor;
} while (cursor);
}
// Usage
for await (const page of fetchAllPages('/users')) {
processUsers(page);
}
最佳实践
安全
- 将 API 密钥存储在环境变量或密钥管理中
- 对所有 API 调用使用 HTTPS
- 验证 Webhook 签名
- 对敏感操作实现请求签名
- 定期轮换 API 密钥
可靠性
- 实现指数退避重试逻辑
- 优雅地处理速率限制
- 设置适当的超时
- 对失败的服务使用熔断器
- 记录所有 API 交互以便调试
性能
- 在适当的时候缓存响应
- 在 API 支持时批量请求
- 对大型响应使用流式传输
- 使用连接池
- 监控 API 使用情况和成本
监控
- 跟踪 API 响应时间
- 在错误率上升时告警
- 监控速率限制消耗
- 记录失败的请求及其上下文
- 为关键集成设置健康检查
常见集成示例
Stripe 支付处理
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
async function createPaymentIntent(amount, currency = 'usd') {
return await stripe.paymentIntents.create({
amount,
currency,
automatic_payment_methods: { enabled: true }
});
}
SendGrid 邮件发送
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
async function sendEmail(to, subject, html) {
await sgMail.send({
to,
from: process.env.FROM_EMAIL,
subject,
html
});
}
Twilio 短信
const twilio = require('twilio')(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_AUTH_TOKEN
);
async function sendSMS(to, body) {
await twilio.messages.create({
to,
from: process.env.TWILIO_PHONE_NUMBER,
body
});
}
故障排除
身份验证问题
- 验证 API 密钥是否正确设置
- 检查令牌过期时间
- 确保 OAuth 作用域正确
- 验证签名生成
速率限制
- 实现客户端速率限制
- 在可用时使用批量端点
- 将请求分散到不同时间
- 考虑升级 API 套餐
超时错误
- 为慢速端点增加超时值
- 实现请求取消
- 对大型负载使用流式传输
- 检查网络连接
集成 API 时,应优先考虑安全性、可靠性和可维护性。在生产部署之前,始终测试错误场景和边缘情况。
评论
支持 Markdown