Python DashアプリをAWS Lambdaにデプロイする完全ガイド

API Gateway設定

API Gateway設定ガイド

API Gatewayの概要

Amazon API Gatewayは、あらゆる規模のRESTful APIを作成、公開、維持、モニタリング、保護するためのAWSサービスです。Python DashアプリケーションをAWS Lambdaにデプロイする場合、API Gatewayを使用してHTTPリクエストをLambda関数にルーティングします。

API Gatewayを使用する主な利点は以下の通りです:

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/)の代わりに、独自のドメイン名を使用することができます。

前提条件

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では、以下の認証方法を使用できます:

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のベストプラクティス

パフォーマンスの最適化

セキュリティの強化

コスト管理

API Gatewayのトラブルシューティング

一般的な問題と解決策

1. 403 Forbidden エラー

考えられる原因と解決策:

2. 500 Internal Server Error

考えられる原因と解決策:

3. CORS関連のエラー

考えられる原因と解決策:

ログの確認方法

# CloudWatchログの確認
aws logs filter-log-events \
  --log-group-name API-Gateway-Execution-Logs_abcdef1234/prod