API統合ガイド
このガイドでは、MBC CQRS Serverlessアプリケーションを外部APIやサービスと統合する方法を説明します。HTTPリクエストの作成、Webhookの処理、リトライロジックの実装、および回復力のある統合を確保するためのパターンを学びます。
このガイドを使用するタイミング
以下のことが必要な場合にこのガイドを使用してください:
- Lambdaハンドラーやサービスからexternal REST APIを呼び出す
- サードパーティサービスからWebhookを受信する
- 外部API呼び出しのリトライとエラーハンドリングを実装する
- 外部システムとの回復力のある統合を構築する
このパターンが解決する問題
| 問題 | 解決策 |
|---|---|
| 外部API呼び出しが断続的に失敗する | 指数バックオフでリトライを実装 |
| サードパーティサービスがアプリにイベントを送信する | 署名検証付きのWebhookエンドポイントを作成 |
| ネットワークタイムアウトがLambda障害を引き起こす | 適切なタイムアウトを設定し、タイムアウトエラーを処理 |
| 外部APIの問題を把握できない | 構造化ログとモニタリングを追加 |
外部APIの呼び出し
HTTPリクエストにfetchを使用する
フレームワークは内部サービスでHTTPリクエストにnode-fetchを使用しています。同じアプローチまたはNode.js互換の任意のHTTPクライアントライブラリを使用できます。
基本的なGETリクエスト
// external-api.service.ts
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class ExternalApiService {
private readonly logger = new Logger(ExternalApiService.name);
private readonly apiBaseUrl: string;
private readonly apiKey: string;
constructor(private readonly configService: ConfigService) {
this.apiBaseUrl = this.configService.get<string>('EXTERNAL_API_URL');
this.apiKey = this.configService.get<string>('EXTERNAL_API_KEY');
}
async getResource(resourceId: string): Promise<any> {
const url = `${this.apiBaseUrl}/resources/${resourceId}`;
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error(`API request failed: ${response.status} ${response.statusText}`);
}
return await response.json();
} catch (error) {
this.logger.error(`Failed to fetch resource ${resourceId}:`, error);
throw error;
}
}
}