API Gateway設定ガイド
API Gatewayの概要
Amazon API Gatewayは、あらゆる規模のRESTful APIを作成、公開、維持、モニタリング、保護するためのAWSサービスです。Python DashアプリケーションをAWS Lambdaにデプロイする場合、API Gatewayを使用してHTTPリクエストをLambda関数にルーティングします。
API Gatewayを使用する主な利点は以下の通りです:
- HTTPエンドポイントの提供
- リクエストとレスポンスの変換
- 認証と認可の管理
- スロットリングとクォータの設定
- APIキーの管理
- カスタムドメイン名のサポート
API Gatewayのタイプ
API Gatewayには主に3つのタイプがあります:
1. REST API
最も一般的なタイプで、RESTfulなAPIを作成するために使用されます。Python Dashアプリケーションでは、通常このタイプを使用します。
2. HTTP API
REST APIよりも低コストで、基本的なAPIプロキシ機能を提供します。シンプルなAPIに適しています。
3. WebSocket API
リアルタイム双方向通信を可能にします。チャットアプリケーションやリアルタイムダッシュボードに適しています。
Python Dashアプリケーションでは、通常REST APIまたはHTTP APIを使用します。WebSocket APIは、特殊なリアルタイム機能が必要な場合にのみ使用します。
API Gatewayの設定方法
Zappaを使用する場合
Zappaを使用する場合、API Gatewayの設定は自動的に行われます。zappa_settings.json
ファイルで以下のような設定が可能です:
{
"dev": {
"app_function": "app.dapp",
"project_name": "dash-lambda",
"aws_region": "ap-northeast-1",
"api_gateway_endpoint_type": "REGIONAL",
"api_key_required": false,
"domain": {
"domain": "example.com",
"route53": true,
"certificate_arn": "arn:aws:acm:us-east-1:123456789012:certificate/abcdef12-3456-7890-abcd-ef1234567890"
}
}
}
AWS SAMを使用する場合
AWS SAMを使用する場合、template.yaml
ファイルでAPI Gatewayの設定を行います:
Resources:
DashFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.9
Events:
DashAPI:
Type: Api
Properties:
Path: /{proxy+}
Method: ANY
DashRoot:
Type: Api
Properties:
Path: /
Method: ANY
ApiGatewayApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
EndpointConfiguration: REGIONAL
Auth:
ApiKeyRequired: false
AWS CLIを使用する場合
AWS CLIを使用する場合、以下のようなコマンドでAPI Gatewayを設定します:
# REST APIの作成
aws apigateway create-rest-api \
--name "Dash Lambda API" \
--description "API for Dash Lambda application" \
--endpoint-configuration "{ \"types\": [\"REGIONAL\"] }"
# ルートリソースIDの取得
aws apigateway get-resources \
--rest-api-id abcdef1234
# プロキシリソースの作成
aws apigateway create-resource \
--rest-api-id abcdef1234 \
--parent-id rootResourceId \
--path-part "{proxy+}"
# ANY メソッドの設定
aws apigateway put-method \
--rest-api-id abcdef1234 \
--resource-id resourceId \
--http-method ANY \
--authorization-type NONE
# Lambda統合の設定
aws apigateway put-integration \
--rest-api-id abcdef1234 \
--resource-id resourceId \
--http-method ANY \
--type AWS_PROXY \
--integration-http-method POST \
--uri arn:aws:apigateway:region:lambda:path/2015-03-31/functions/arn:aws:lambda:region:accountId:function:functionName/invocations
カスタムドメインの設定
API Gatewayのデフォルトドメイン(https://abcdef1234.execute-api.region.amazonaws.com/stage/
)の代わりに、独自のドメイン名を使用することができます。
前提条件
- 所有しているドメイン名
- AWS Certificate Manager(ACM)で発行された証明書
- Route 53でホストされているドメイン(オプション)
Zappaを使用する場合
{
"dev": {
"app_function": "app.dapp",
"project_name": "dash-lambda",
"aws_region": "ap-northeast-1",
"domain": {
"domain": "api.example.com",
"certificate_arn": "arn:aws:acm:us-east-1:123456789012:certificate/abcdef12-3456-7890-abcd-ef1234567890",
"route53": true
}
}
}
設定後、以下のコマンドを実行します:
zappa certify dev
AWS CLIを使用する場合
# カスタムドメイン名の作成
aws apigateway create-domain-name \
--domain-name api.example.com \
--regional-certificate-arn arn:aws:acm:region:accountId:certificate/certificateId \
--endpoint-configuration "{ \"types\": [\"REGIONAL\"] }"
# ベースパスマッピングの作成
aws apigateway create-base-path-mapping \
--domain-name api.example.com \
--rest-api-id abcdef1234 \
--stage stage
DNS設定
API Gatewayのカスタムドメイン名を作成すると、ターゲットドメイン名が提供されます。このドメイン名を使用して、DNSプロバイダーでCNAMEレコードを作成します。
# Route 53を使用する場合
aws route53 change-resource-record-sets \
--hosted-zone-id Z1234567890ABC \
--change-batch '{
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "api.example.com",
"Type": "CNAME",
"TTL": 300,
"ResourceRecords": [
{
"Value": "d-abcdef1234.execute-api.region.amazonaws.com"
}
]
}
}
]
}'
API Gatewayのステージ
API Gatewayでは、複数のステージ(開発、テスト、本番など)を作成することができます。各ステージは独立したデプロイメントを持ち、異なる設定を適用することができます。
ステージの作成
aws apigateway create-deployment \
--rest-api-id abcdef1234 \
--stage-name prod
ステージ変数の設定
ステージ変数を使用して、異なる環境に応じた設定を行うことができます。
aws apigateway update-stage \
--rest-api-id abcdef1234 \
--stage-name prod \
--patch-operations op=replace,path=/variables/environment,value=production
Dashアプリケーションでのステージ名の処理
API Gatewayのステージ名はURLのパスに含まれるため、Dashアプリケーションではrequests_pathname_prefix
を設定する必要があります。
# Zappaの場合
{
"dev": {
"environment_variables": {
"DASH_REQUESTS_PATHNAME_PREFIX": "/dev/"
}
}
}
# 直接設定する場合
app = dash.Dash(__name__, requests_pathname_prefix='/prod/')
API Gatewayのセキュリティ設定
認証方法
API Gatewayでは、以下の認証方法を使用できます:
- IAM認証
- Cognito認証
- Lambda認証
- APIキー認証
APIキーの設定
# APIキーの作成
aws apigateway create-api-key \
--name "DashAppKey" \
--description "API key for Dash application" \
--enabled
# 使用量プランの作成
aws apigateway create-usage-plan \
--name "DashAppPlan" \
--description "Usage plan for Dash application" \
--api-stages "apiId=abcdef1234,stage=prod" \
--throttle "rateLimit=10,burstLimit=5" \
--quota "limit=1000,period=MONTH"
# APIキーを使用量プランに関連付ける
aws apigateway create-usage-plan-key \
--usage-plan-id planId \
--key-id keyId \
--key-type "API_KEY"
CORSの設定
クロスオリジンリソース共有(CORS)を設定することで、異なるドメインからのAPIアクセスを許可することができます。
# CORSの設定
aws apigateway put-method-response \
--rest-api-id abcdef1234 \
--resource-id resourceId \
--http-method ANY \
--status-code 200 \
--response-parameters "method.response.header.Access-Control-Allow-Origin=false"
aws apigateway put-integration-response \
--rest-api-id abcdef1234 \
--resource-id resourceId \
--http-method ANY \
--status-code 200 \
--response-parameters "method.response.header.Access-Control-Allow-Origin='*'"
API Gatewayのモニタリング
CloudWatchメトリクス
API Gatewayは、リクエスト数、レイテンシー、エラー率などのメトリクスをCloudWatchに送信します。
aws cloudwatch get-metric-statistics \
--namespace "AWS/ApiGateway" \
--metric-name "Count" \
--dimensions Name=ApiName,Value=DashLambdaAPI Name=Stage,Value=prod \
--start-time 2025-03-01T00:00:00Z \
--end-time 2025-03-22T00:00:00Z \
--period 86400 \
--statistics Sum
アクセスログの有効化
aws apigateway update-stage \
--rest-api-id abcdef1234 \
--stage-name prod \
--patch-operations op=replace,path=/accessLogSettings/destinationArn,value=arn:aws:logs:region:accountId:log-group:API-Gateway-Access-Logs:* op=replace,path=/accessLogSettings/format,value='{ "requestId":"$context.requestId", "ip": "$context.identity.sourceIp", "caller":"$context.identity.caller", "user":"$context.identity.user", "requestTime":"$context.requestTime", "httpMethod":"$context.httpMethod", "resourcePath":"$context.resourcePath", "status":"$context.status", "protocol":"$context.protocol", "responseLength":"$context.responseLength" }'
X-Ray統合
AWS X-Rayを使用して、APIリクエストのトレースを行うことができます。
aws apigateway update-stage \
--rest-api-id abcdef1234 \
--stage-name prod \
--patch-operations op=replace,path=/tracingEnabled,value=true
API Gatewayのベストプラクティス
パフォーマンスの最適化
- キャッシュを有効にして、頻繁にアクセスされるリソースのレスポンスタイムを改善する
- リクエストとレスポンスの変換を最小限に抑える
- 大きなペイロードの場合は、直接S3を使用することを検討する
セキュリティの強化
- 最小権限の原則に従ってIAMポリシーを設定する
- 機密性の高いAPIには認証を必須にする
- WAF(Web Application Firewall)を使用して、一般的な攻撃から保護する
- APIキーを定期的にローテーションする
コスト管理
- 使用量プランを設定して、APIの使用量を制限する
- キャッシュを使用して、Lambda関数の呼び出し回数を減らす
- 不要なステージやAPIは削除する
API Gatewayのトラブルシューティング
一般的な問題と解決策
1. 403 Forbidden エラー
考えられる原因と解決策:
- IAM認証が有効になっている場合、適切な認証情報が提供されていない
- APIキーが必要な場合、APIキーが提供されていない、または無効
- リソースポリシーがアクセスを制限している
2. 500 Internal Server Error
考えられる原因と解決策:
- Lambda関数でエラーが発生している(CloudWatchログを確認)
- 統合リクエストまたはレスポンスの設定が正しくない
- Lambda関数のタイムアウトが短すぎる
3. CORS関連のエラー
考えられる原因と解決策:
- CORSが正しく設定されていない
- OPTIONSメソッドが設定されていない
- 必要なCORSヘッダーが返されていない
ログの確認方法
# CloudWatchログの確認
aws logs filter-log-events \
--log-group-name API-Gateway-Execution-Logs_abcdef1234/prod