API Gateway + Lambda 統合

API Gateway と Lambda を組み合わせたサーバーレス API の構築パターン

AWSサーバーレス

API Gateway + Lambda とは

API Gateway + Lambda は、AWS のサーバーレス API の基本構成で、API Gateway が HTTP リクエストを受け、Lambda 関数を呼び出してレスポンスを返す。インフラ管理不要で、リクエスト数に応じた従量課金。

HTTP API vs REST API

観点 HTTP API REST API
レイテンシ 低い やや高い
コスト $1.00/100 万 $3.50/100 万
CORS 自動処理 手動設定
認証 JWT (Cognito, OIDC) IAM, Cognito, Lambda Authorizer
WebSocket
推奨 ✅ (新規プロジェクト) △ (高度な機能が必要な場合)

SAM での定義

MyFunction:
  Type: AWS::Serverless::Function
  Properties:
    Runtime: nodejs22.x
    Handler: index.handler
    Events:
      GetOrders:
        Type: HttpApi
        Properties:
          Path: /orders
          Method: GET
      CreateOrder:
        Type: HttpApi
        Properties:
          Path: /orders
          Method: POST

Lambda ハンドラ

export const handler = async (event: APIGatewayProxyEventV2) => {
  const method = event.requestContext.http.method;
  const path = event.requestContext.http.path;

  if (method === 'GET' && path === '/orders') {
    const orders = await getOrders();
    return { statusCode: 200, body: JSON.stringify(orders) };
  }

  if (method === 'POST' && path === '/orders') {
    const body = JSON.parse(event.body ?? '{}');
    const order = await createOrder(body);
    return { statusCode: 201, body: JSON.stringify(order) };
  }

  return { statusCode: 404, body: JSON.stringify({ error: 'Not found' }) };
};

認証

MyApi:
  Type: AWS::Serverless::HttpApi
  Properties:
    Auth:
      DefaultAuthorizer: CognitoAuth
      Authorizers:
        CognitoAuth:
          JwtConfiguration:
            issuer: !Sub https://cognito-idp.${AWS::Region}.amazonaws.com/${UserPool}
            audience: [!Ref UserPoolClient]

パフォーマンス最適化

対策 効果
Lambda メモリ増加 CPU も増加、レイテンシ低下
Provisioned Concurrency コールドスタート排除
esbuild バンドル デプロイサイズ削減
CloudFront 統合 エッジキャッシュ

コスト

HTTP API: $1.00/100 万リクエスト
Lambda: $0.20/100 万リクエスト + 実行時間
合計: 月 100 万リクエスト ≈ $1.20 + 実行時間

体系的に学ぶなら関連書籍を参照してほしい。

関連用語