API Integration Specialist
サードパーティAPIとの統合において、適切な認証・エラーハンドリング・レート制限・リトライロジックを実装するスペシャリスト。REST API、GraphQLエンドポイント、webhook、または外部サービスを統合する際に活用してください。OAuthフロー、APIキー管理、リクエスト/レスポンスの変換、堅牢なAPIクライアントの構築を得意とします。
description の原文を見る
Expert in integrating third-party APIs with proper authentication, error handling, rate limiting, and retry logic. Use when integrating REST APIs, GraphQL endpoints, webhooks, or external services. Specializes in OAuth flows, API key management, request/response transformation, and building robust API clients.
SKILL.md 本文
API Integration Specialist
外部APIをアプリケーションに統合するための専門的なガイダンス。本番環境対応のパターン、セキュリティのベストプラクティス、包括的なエラーハンドリングを提供します。
このスキルを使用する場合
以下の場合にこのスキルを使用してください:
- サードパーティAPI (Stripe、Twilio、SendGrid など) の統合
- APIクライアントライブラリやラッパーの構築
- OAuth 2.0、APIキー、JWT認証の実装
- Webhook とイベント駆動型統合のセットアップ
- レート制限、リトライ、サーキットブレーカーの処理
- アプリケーション使用のためのAPI応答の変換
- API統合の問題のデバッグ
コア統合原則
1. 認証とセキュリティ
APIキー管理:
// キーは環境変数に保存し、コードには決して記述しない
const apiClient = new APIClient({
apiKey: process.env.SERVICE_API_KEY,
baseURL: process.env.SERVICE_BASE_URL
});
OAuth 2.0 フロー:
// 認可コードフロー
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();
// コードをトークンと交換
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}`);
// 外部API形式を内部モデルに変換
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; // クライアントエラーはリトライしない
}
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); // 1分あたり100リクエスト
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();
}
// リソースメソッド
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);
}
// 使用方法
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 SMS
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を統合する際には、セキュリティ、信頼性、保守性を優先してください。本番環境へのデプロイの前に、必ずエラーシナリオとエッジケースをテストしてください。
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- davila7
- ライセンス
- MIT
- 最終更新
- 不明
Source: https://github.com/davila7/claude-code-templates / ライセンス: MIT
関連スキル
doubt-driven-development
重要な判断はすべて、本番環境への展開前に新しい視点から対抗的レビューを実施します。速度より正確性が重要な場合、不慣れなコードを扱う場合、本番環境・セキュリティに関わるロジック・取り消し不可の操作など影響度が高い場合、または後でバグを修正するよりも今検証する方が効率的な場合に活用してください。
apprun-skills
TypeScriptを使用したAppRunアプリケーションのMVU設計に関する総合的なガイダンスが得られます。コンポーネントパターン、イベントハンドリング、状態管理(非同期ジェネレータを含む)、パラメータと保護機能を備えたルーティング・ナビゲーション、vistestを使用したテストに対応しています。AppRunコンポーネントの設計・レビュー、ルートの配線、状態フローの管理、AppRunテストの作成時に活用してください。
desloppify
コードベースのヘルスチェックと技術負債の追跡ツールです。コード品質、技術負債、デッドコード、大規模ファイル、ゴッドクラス、重複関数、コードスメル、命名規則の問題、インポートサイクル、結合度の問題についてユーザーが質問した場合に使用してください。また、ヘルススコアの確認、次の改善項目の提案、クリーンアップ計画の作成をリクエストされた際にも対応します。29言語に対応しています。
debugging-and-error-recovery
テストが失敗したり、ビルドが壊れたり、動作が期待と異なったり、予期しないエラーが発生したりした場合に、体系的な根本原因デバッグをガイドします。推測ではなく、根本原因を見つけて修正するための体系的なアプローチが必要な場合に使用してください。
test-driven-development
テスト駆動開発により実装を進めます。ロジックの実装、バグの修正、動作の変更など、あらゆる場面で活用できます。コードが正常に動作することを証明する必要がある場合、バグ報告を受けた場合、既存機能を修正する予定がある場合に使用してください。
incremental-implementation
変更を段階的に実施します。複数のファイルに影響する機能や変更を実装する場合に使用してください。大量のコードを一度に書こうとしている場合や、タスクが一度では完結できないほど大きい場合に活用します。