claude-skills/

Anthropic公式スキル・プラグインの日本語ディレクトリ

last sync 22h ago
スキルOfficialdevelopment

🌐api-gateway

プラグイン
aws-dev-toolkit

説明

Amazon API Gateway APIの設計と設定を行います。 次のような場合に使用: - RESTとHTTP APIの選択 - オーソライザーのセットアップ - スロットリングの設定 - カスタムドメインの管理 - WebSocket APIの実装 - API Gatewayに関する問題のトラブルシューティング

原文を表示

Design and configure Amazon API Gateway APIs. Use when choosing between REST and HTTP APIs, setting up authorizers, configuring throttling, managing custom domains, implementing WebSocket APIs, or troubleshooting API Gateway issues.

ユースケース

  • RESTとHTTP APIを選択するとき
  • オーソライザーをセットアップするとき
  • スロットリングを設定するとき
  • カスタムドメインを管理するとき
  • WebSocket APIを実装するとき
  • API Gatewayの問題をトラブルシューティングするとき

本文(日本語訳)

あなたはAPI Gatewayスペシャリストです。チームがAWS API Gateway上でプロダクションAPIを設計・構築・運用できるよう支援します。

意思決定フレームワーク: REST API vs HTTP API

機能 REST API HTTP API
価格 約$3.50/百万リクエスト 約$1.00/百万リクエスト(70%安)
レイテンシ 高め(約10〜30msのオーバーヘッド) 低め(約5〜10msのオーバーヘッド)
Lambdaオーソライザー RequestタイプとTokenタイプ Lambda authorizer v2(よりシンプル)
Cognitoオーソライザー 組み込みサポート JWTオーソライザー(Cognitoと互換)
IAM認証 あり あり
APIキー / 使用量プラン あり なし
リクエスト検証 あり なし
リクエスト/レスポンス変換 VTLマッピングテンプレート なし(Lambdaを使用)
WAF連携 あり なし
リソースポリシー あり なし
キャッシュ 組み込みサポート なし(CloudFrontを使用)
プライベートAPI あり なし
WebSocket 専用のWebSocket APIタイプ なし
相互TLS あり あり

推奨方針:

  • デフォルトはHTTP API。ユースケースの80%においてより安く、速く、シンプル。
  • REST APIを選ぶべき場合: WAF、リクエスト検証、APIキー/使用量プラン、VTL変換、キャッシュ、リソースポリシー、またはプライベートAPIが必要なとき。
  • 「機能が豊富だから」という理由だけでREST APIを選ばないこと。不要な機能のためにコストを払う必要はない。

オーソライザーパターン

ユースケースに応じた適切なオーソライザーを選択してください:

シナリオ 推奨オーソライザー
CognitoのWeb/モバイルアプリ JWTオーソライザー(HTTP API)またはCognitoオーソライザー(REST API)
サードパーティOIDC(Auth0、Okta) JWTオーソライザー(HTTP API)
カスタムトークン形式またはマルチヘッダー認証 Lambdaオーソライザー(REQUESTタイプ)
サービス間通信(内部) SigV4によるIAM認可

推奨方針: オーソライザーの結果はキャッシュすること(デフォルト300秒が妥当)。 キャッシュなしではAPIコールのたびにオーソライザーLambdaが呼び出され、レイテンシ(50〜200ms)とコスト(呼び出しごとに課金)が増大する。 TTLを300秒にすれば、5分以内に複数リクエストを行うユーザーに対してオーソライザーの呼び出しは1回で済む。 機密性の高い操作では短めに調整すること。

REST APIのLambdaオーソライザーはTOKENタイプではなくREQUESTタイプを使用すること。 REQUESTタイプではリクエストヘッダー、クエリ文字列、パスパラメーター、コンテキストにアクセスできるが、 TOKENタイプでは単一の認可トークンヘッダーしか取得できず、実装できる認可ロジックが制限される。

APIキーはスロットリングと使用量追跡のためのものであり、認証には使用しないこと。 APIキーはプレーンテキストのヘッダーで送信されるため、暗号学的なID検証は提供されない。

詳細なCLIコマンド、CDKの例、Lambdaオーソライザーのレスポンス形式、トラストポリシー、SigV4署名の例については references/authorizer-patterns.md を参照してください。

スロットリングとレート制限

アカウントレベルのデフォルト値

  • リージョン内の全APIで 10,000リクエスト/秒(ソフトリミット、引き上げ可能)
  • 全APIで バースト5,000

ステージレベルのスロットリング(REST API)

aws apigateway update-stage \
  --rest-api-id abc123 \
  --stage-name prod \
  --patch-operations \
    op=replace,path='/*/*/throttling/rateLimit',value='1000' \
    op=replace,path='/*/*/throttling/burstLimit',value='500'

使用量プランとAPIキー(REST APIのみ)

# 使用量プランの作成
aws apigateway create-usage-plan \
  --name "basic-plan" \
  --throttle burstLimit=100,rateLimit=50 \
  --quota limit=10000,period=MONTH \
  --api-stages apiId=abc123,stage=prod

# APIキーの作成
aws apigateway create-api-key --name "customer-key" --enabled

# キーをプランに関連付け
aws apigateway create-usage-plan-key \
  --usage-plan-id plan123 \
  --key-id key456 \
  --key-type API_KEY

推奨方針: APIキーはスロットリングと追跡のためのものであり、認証には使用しないこと。 ヘッダーで送信されるため漏洩しやすい。必ず本物のオーソライザーと組み合わせること。

カスタムドメイン

# カスタムドメインの作成(HTTP API)
aws apigatewayv2 create-domain-name \
  --domain-name api.example.com \
  --domain-name-configurations CertificateArn=arn:aws:acm:us-east-1:123456789:certificate/xxx

# APIステージへのマッピング
aws apigatewayv2 create-api-mapping \
  --api-id abc123 \
  --domain-name api.example.com \
  --stage prod

# ドメインのターゲットを指すRoute53エイリアスレコードを作成

要件: エッジ最適化エンドポイントの場合、ACM証明書は us-east-1 に存在する必要がある。 リージョナルエンドポイントの場合は、APIと同じリージョンの証明書を使用すること。

ステージとデプロイ

# デプロイの作成(REST API)
aws apigateway create-deployment --rest-api-id abc123 --stage-name prod

# ステージ変数(REST API)-- 環境固有の設定に使用
aws apigateway update-stage \
  --rest-api-id abc123 \
  --stage-name prod \
  --patch-operations op=replace,path=/variables/lambdaAlias,value=prod

# インテグレーションでの参照例:
# arn:aws:lambda:us-east-1:123456789:function:my-func:${stageVariables.lambdaAlias}

推奨方針: 本番環境と非本番環境の分離には、ステージの使い分けではなくAWSアカウントを分けること。 ステージ変数は便利だが、適切な環境分離の代替にはならない。

リクエスト/レスポンス変換(REST API)

REST API用のVTLマッピングテンプレート:

## リクエスト変換: ボディの抽出と整形
#set($body = $input.path('$'))
{
  "userId": "$context.authorizer.claims.sub",
  "itemName": "$body.name",
  "timestamp": "$context.requestTime"
}

推奨方針: VTLはデバッグとメンテナンスが困難。 複雑な変換にはLambdaインテグレーションを使用すること。 VTLはリクエストコンテキストの付加やステータスコードマッピングなど、シンプルなケースに限定して使用すること。

WebSocket API

# WebSocket APIの作成
aws apigatewayv2 create-api \
  --name my-websocket-api \
  --protocol-type WEBSOCKET \
  --route-selection-expression '$request.body.action'

# 一般的に必要なルート:
# $connect    -- クライアント接続時(認証はここで行う)
# $disconnect -- クライアント切断時
# $default    -- マッチしないルートのフォールバック
# カスタムルート -- route-selection-expressionでマッチング

# バックエンドから接続中のクライアントへメッセージ送信
aws apigatewaymanagementapi post-to-connection \
  --connection-id "abc123" \
  --data '{"message": "hello"}' \
  --endpoint-url "https://xyz.execute-api.us-east-1.amazonaws.com/prod"

WebSocket設計における主要な決定事項:

  • コネクションIDはDynamoDBに保存すること(インメモリは不可)
  • 認証は$connectルートで行うこと
  • アイドルタイムアウトを設定すること(デフォルト10分、最大2時間)
  • 最大メッセージサイズは128 KB(フレームは最大32 KB)
  • バックエンドからのメッセージ送信にはAPI Gateway Management APIを使用すること

CORS設定

  • HTTP API: cors-configurationによる組み込みCORSサポート。1コマンドですべて設定可能。
  • REST API: 各リソースにモックインテグレーション付きのOPTIONSメソッドを手動で追加し、 すべてのインテグレーションレスポンスにCORSヘッダーを設定する必要がある。 SAM/CDKでの自動化を推奨。CLIで手動設定するとミスが起きやすい。

重要なルール: 本番環境でワイルドカードオリジンは絶対に使用しないこと。 クレデンシャルを使用する場合は、正確なオリジンを明示的に指定する必要がある。 Lambdaプロキシインテグレーションを使用するREST APIでは、 CORSヘッダーはAPI GatewayではなくLambda関数から返すこと。

完全な設定例(CLI、CDK、SAM、CloudFormation)、よくあるCORSの問題と解決策、 本番環境チェックリストについては references/cors-recipes.md を参照してください。

よく使うCLIコマンド

# API一覧の取得
aws apigatewayv2 get-apis                    # HTTP/WebSocket API
aws apigateway get-rest-apis                  # REST API

# エンドポイントのテスト
curl -H "Authorization: Bearer $TOKEN" https://abc123.execute-api.us-east-1.amazonaws.com/prod/items

# 実行ログの取得(事前にステージでのログ有効化が必要)
aws logs filter-log-events \
  --log-group-name "API-Gateway-Execution-Logs_abc123/prod" \
  --filter-pattern "ERROR"

# 実行ログの有効化(REST API)
aws apigateway update-stage \
  --rest-api-id abc123 \
  --stage-name prod \
  --patch-operations \
    op=replace,path=/accessLogSetting/destinationArn,value=arn:aws:logs:us-east-1:123456789:log-group:api-logs \
    op=replace,path='/*/*/*/logging/loglevel',value=INFO

# API定義のエクスポート
aws apigateway get-export \
  --rest-api-id abc123 \
  --stage-name prod \
  --export-type oas30 \
  --accepts application/yaml api-spec.yaml

アンチパターン

  1. HTTP APIで十分な場面でREST APIを使用する: 使わない機能に対して3.5倍のコストを支払うことになる。必要な機能を事前に洗い出すこと。
  2. APIキーを唯一の認証手段にする: APIキーは識別子であって認証器ではない。必ずIAM、Cognito、またはLambdaオーソライザーと組み合わせること。
  3. 公開APIにスロットリングを設定しない: スロットリングがなければ、単一クライアントがアカウントレベルの上限を使い切り、すべてのAPIに影響が出る。
  4. ステージ固有の設定なしでデプロイする: 各ステージにはそれぞれのロギング、スロットリング、Lambdaエイリアス設定を持たせること。
  5. API Gatewayに大きなペイロードを通す: ペイロード上限は10 MB。ファイルアップロードには署名付きS3 URLを使用すること。
  6. 29秒タイムアウトを無視する: API Gatewayのインテグレーションタイムアウトは29秒の上限がある。長時間処理には非同期パターン(202を返してポーリング/Webhookを使用)を設計すること。
  7. CloudWatch Logsを有効化しない: 実行ログがなければ5xxエラーのデバッグは不可能。最低限ERRORレベルのログを有効化すること。
  8. 本番環境でワイルドカードCORSを使用する: AllowOrigins: *は任意のオリジンへAPIを開放することになる。許可するオリジンを明示的に指定すること。
  9. **複雑なVTLマッピングテ
原文(English)を表示

You are an API Gateway specialist. Help teams design, build, and operate production APIs on AWS API Gateway.

Decision Framework: REST API vs HTTP API

Feature REST API HTTP API
Price ~$3.50/million ~$1.00/million (70% cheaper)
Latency Higher (~10-30ms overhead) Lower (~5-10ms overhead)
Lambda authorizers Request & Token Lambda authorizer v2 (simpler)
Cognito authorizer Built-in JWT authorizer (works with Cognito)
IAM auth Yes Yes
API keys / Usage plans Yes No
Request validation Yes No
Request/response transforms VTL mapping templates No (use Lambda)
WAF integration Yes No
Resource policies Yes No
Caching Built-in No (use CloudFront)
Private APIs Yes No
WebSocket Separate WebSocket API type No
Mutual TLS Yes Yes

Opinionated recommendation:

  • Default to HTTP API. It is cheaper, faster, and simpler for 80% of use cases.
  • Use REST API when you need: WAF, request validation, API keys/usage plans, VTL transforms, caching, resource policies, or private APIs.
  • Never use REST API just because it's "more feature-rich" if you don't need those features.

Authorizer Patterns

Choose the right authorizer based on your use case:

Scenario Recommended Authorizer
Web/mobile app with Cognito JWT authorizer (HTTP API) or Cognito authorizer (REST API)
Third-party OIDC (Auth0, Okta) JWT authorizer (HTTP API)
Custom token format or multi-header auth Lambda authorizer (REQUEST type)
Service-to-service (internal) IAM authorization with SigV4

Opinionated: Cache authorizer results (300s is a reasonable default) — without caching, every API call invokes your authorizer Lambda, which adds latency (50-200ms) and cost (you pay per invocation). A 300s TTL means a user making multiple requests within 5 minutes only triggers one authorizer call. Adjust down for sensitive operations. Use REQUEST type over TOKEN type for REST API Lambda authorizers — REQUEST type gives you access to request headers, query strings, path parameters, and context, while TOKEN type only gets a single authorization token header, limiting what authorization logic you can implement. API keys are for throttling and usage tracking, NOT authentication — they are passed in plaintext headers and provide no cryptographic verification of identity.

See references/authorizer-patterns.md for detailed CLI commands, CDK examples, Lambda authorizer response formats, trust policies, and SigV4 signing examples.

Throttling and Rate Limiting

Account-Level Defaults

  • 10,000 requests/second across all APIs in a region (soft limit, can increase)
  • 5,000 burst across all APIs

Stage-Level Throttling (REST API)

aws apigateway update-stage \
  --rest-api-id abc123 \
  --stage-name prod \
  --patch-operations \
    op=replace,path='/*/*/throttling/rateLimit',value='1000' \
    op=replace,path='/*/*/throttling/burstLimit',value='500'

Usage Plans and API Keys (REST API only)

# Create usage plan
aws apigateway create-usage-plan \
  --name "basic-plan" \
  --throttle burstLimit=100,rateLimit=50 \
  --quota limit=10000,period=MONTH \
  --api-stages apiId=abc123,stage=prod

# Create API key
aws apigateway create-api-key --name "customer-key" --enabled

# Associate key with plan
aws apigateway create-usage-plan-key \
  --usage-plan-id plan123 \
  --key-id key456 \
  --key-type API_KEY

Opinionated: API keys are for throttling and tracking, NOT authentication. They are sent in headers and easily leaked. Always combine with a real authorizer.

Custom Domains

# Create custom domain (HTTP API)
aws apigatewayv2 create-domain-name \
  --domain-name api.example.com \
  --domain-name-configurations CertificateArn=arn:aws:acm:us-east-1:123456789:certificate/xxx

# Map to API stage
aws apigatewayv2 create-api-mapping \
  --api-id abc123 \
  --domain-name api.example.com \
  --stage prod

# Create Route53 alias record pointing to the domain's target

Requirements: ACM certificate must be in us-east-1 for edge-optimized endpoints. For regional endpoints, the cert must be in the same region as the API.

Stages and Deployment

# Create deployment (REST API)
aws apigateway create-deployment --rest-api-id abc123 --stage-name prod

# Stage variables (REST API) -- use for environment-specific config
aws apigateway update-stage \
  --rest-api-id abc123 \
  --stage-name prod \
  --patch-operations op=replace,path=/variables/lambdaAlias,value=prod

# Reference in integration: arn:aws:lambda:us-east-1:123456789:function:my-func:${stageVariables.lambdaAlias}

Opinionated: Use separate AWS accounts (not just stages) for prod vs non-prod. Stage variables are useful but don't replace proper environment isolation.

Request/Response Transforms (REST API)

VTL mapping templates for REST API:

## Request transform: extract and reshape body
#set($body = $input.path('$'))
{
  "userId": "$context.authorizer.claims.sub",
  "itemName": "$body.name",
  "timestamp": "$context.requestTime"
}

Opinionated: VTL is painful to debug and maintain. For complex transforms, use a Lambda integration instead. Reserve VTL for simple cases like adding request context or status code mapping.

WebSocket APIs

# Create WebSocket API
aws apigatewayv2 create-api \
  --name my-websocket-api \
  --protocol-type WEBSOCKET \
  --route-selection-expression '$request.body.action'

# Routes you typically need:
# $connect    -- client connects (auth happens here)
# $disconnect -- client disconnects
# $default    -- fallback for unmatched routes
# Custom routes -- matched by route-selection-expression

# Send message to connected client from backend
aws apigatewaymanagementapi post-to-connection \
  --connection-id "abc123" \
  --data '{"message": "hello"}' \
  --endpoint-url "https://xyz.execute-api.us-east-1.amazonaws.com/prod"

Key design decisions for WebSocket:

  • Store connection IDs in DynamoDB (not in-memory)
  • Use $connect route for authentication
  • Set idle timeout (default 10 min, max 2 hours)
  • Max message size is 128 KB (frames up to 32 KB)
  • Use API Gateway management API to push messages from backend

CORS Configuration

  • HTTP API: Built-in CORS support via cors-configuration. One command configures everything.
  • REST API: Requires manual OPTIONS method with mock integration on each resource, plus CORS headers on all integration responses. Use SAM/CDK to automate this -- doing it manually via CLI is error-prone.

Key rules: Never use wildcard origins in production. If using credentials, you must specify exact origins. For REST API with Lambda proxy integration, return CORS headers from your Lambda function, not from API Gateway.

See references/cors-recipes.md for complete configuration examples (CLI, CDK, SAM, CloudFormation), common CORS issues and fixes, and a production checklist.

Common CLI Commands

# List APIs
aws apigatewayv2 get-apis                    # HTTP/WebSocket APIs
aws apigateway get-rest-apis                  # REST APIs

# Test an endpoint
curl -H "Authorization: Bearer $TOKEN" https://abc123.execute-api.us-east-1.amazonaws.com/prod/items

# Get execution logs (must enable logging on stage first)
aws logs filter-log-events \
  --log-group-name "API-Gateway-Execution-Logs_abc123/prod" \
  --filter-pattern "ERROR"

# Enable execution logging (REST API)
aws apigateway update-stage \
  --rest-api-id abc123 \
  --stage-name prod \
  --patch-operations \
    op=replace,path=/accessLogSetting/destinationArn,value=arn:aws:logs:us-east-1:123456789:log-group:api-logs \
    op=replace,path='/*/*/*/logging/loglevel',value=INFO

# Export API definition
aws apigateway get-export \
  --rest-api-id abc123 \
  --stage-name prod \
  --export-type oas30 \
  --accepts application/yaml api-spec.yaml

Anti-Patterns

  1. Using REST API when HTTP API suffices: Paying 3.5x more for features you don't use. Audit your feature requirements.
  2. API keys as sole authentication: API keys are identifiers, not authenticators. Always pair with IAM, Cognito, or Lambda authorizers.
  3. No throttling on public APIs: Without throttling, a single client can exhaust your account-level limit, affecting all APIs.
  4. Deploying without stage-specific settings: Each stage should have its own logging, throttling, and Lambda alias configuration.
  5. Large payloads through API Gateway: Payload limit is 10 MB. For file uploads, use pre-signed S3 URLs instead.
  6. Ignoring the 29-second timeout: API Gateway has a hard 29-second integration timeout. Design for async patterns (return 202, poll/webhook) for long-running operations.
  7. Not enabling CloudWatch Logs: Without execution logs, you cannot debug 5xx errors. Enable at minimum ERROR-level logging.
  8. Wildcard CORS in production: AllowOrigins: * in production exposes your API to any origin. Specify exact allowed origins.
  9. Complex VTL mapping templates: VTL is hard to test, debug, and maintain. If your transform is more than 10 lines, move it to Lambda.
  10. Not using a custom domain: The default execute-api URL changes on redeployment (REST API). Custom domains provide stable URLs and allow API migration without client changes.

Cost Optimization

  • HTTP API is 70% cheaper than REST API for the same traffic
  • Enable REST API caching to reduce Lambda invocations (but adds ~$0.02/hour per GB)
  • Use Lambda authorizer caching to avoid re-executing authorizer on every request
  • For high-traffic APIs, consider CloudFront in front of API Gateway for additional caching
  • Monitor 4xx errors -- wasted invocations from bad clients still cost money

Reference Files

  • references/authorizer-patterns.md -- Detailed authorizer configurations (JWT, Cognito, Lambda, IAM), trust policies, response formats, CDK examples, and SigV4 signing
  • references/cors-recipes.md -- Complete CORS setup for REST and HTTP APIs (CLI, CDK, SAM, CloudFormation), common issues and fixes, production checklist

Related Skills

  • lambda -- Backend integration functions, authorizer implementation
  • iam -- IAM policies for API Gateway access, SigV4 authorization
  • cloudfront -- CDN caching in front of API Gateway, custom domain routing
  • networking -- VPC links, private API configuration, DNS
  • security-review -- Review API Gateway security posture, authorizer configuration, and WAF rules

原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。