API Gateway WebSocket:モック統合の実装
バックエンドの Lambda を使わず、モック統合のみで API Gateway WebSocket API を構築し、あらかじめ用意したレスポンスを返します。
API Gateway のモック統合を使うと、バックエンドを用意せずに、あらかじめ定義した WebSocket レスポンスを返せます。実際のビジネスロジックを実装する前に、ルーティングやレスポンス形式を検証する用途に便利です。
Integrations for WebSocket APIs in API Gateway
構築
- 68 行目の
$input.path('$.messageId')によってmessageIdが渡されます。 - 77 行目と 84 行目にある統合レスポンスのキーには
statusCodeを指定します。 - 85〜87 行目にある
messageルートのレスポンステンプレートは、messageIdの値に応じてレスポンスを切り替えます。
AWSTemplateFormatVersion: 2010-09-09Description: API Gateway WebSocket with Mock IntegrationResources: ApiGatewayV2Api: Type: AWS::ApiGatewayV2::Api Properties: Name: api-gateway-websocket-with-mock-integration ProtocolType: WEBSOCKET RouteSelectionExpression: $request.body.action
ApiGatewayV2Stage: Type: AWS::ApiGatewayV2::Stage Properties: StageName: production ApiId: !Ref ApiGatewayV2Api AutoDeploy: true
ApiGatewayV2RouteOnConnect: Type: AWS::ApiGatewayV2::Route Properties: ApiId: !Ref ApiGatewayV2Api RouteKey: $connect RouteResponseSelectionExpression: $default Target: !Sub integrations/${ApiGatewayV2IntegrationOnConnect}
ApiGatewayV2RouteOnMessage: Type: AWS::ApiGatewayV2::Route Properties: ApiId: !Ref ApiGatewayV2Api RouteKey: message RouteResponseSelectionExpression: $default Target: !Sub integrations/${ApiGatewayV2IntegrationOnMessage}
ApiGatewayV2RouteResponseOnConnect: Type: AWS::ApiGatewayV2::RouteResponse Properties: ApiId: !Ref ApiGatewayV2Api RouteResponseKey: $default RouteId: !Ref ApiGatewayV2RouteOnConnect
ApiGatewayV2RouteResponseOnMessage: Type: AWS::ApiGatewayV2::RouteResponse Properties: ApiId: !Ref ApiGatewayV2Api RouteResponseKey: $default RouteId: !Ref ApiGatewayV2RouteOnMessage
ApiGatewayV2IntegrationOnConnect: Type: AWS::ApiGatewayV2::Integration Properties: ApiId: !Ref ApiGatewayV2Api ConnectionType: INTERNET IntegrationType: MOCK PassthroughBehavior: WHEN_NO_MATCH RequestTemplates: '$default': '{"statusCode": 200}' TimeoutInMillis: 29000 PayloadFormatVersion: '1.0'
ApiGatewayV2IntegrationOnMessage: Type: AWS::ApiGatewayV2::Integration Properties: ApiId: !Ref ApiGatewayV2Api ConnectionType: INTERNET IntegrationType: MOCK PassthroughBehavior: WHEN_NO_MATCH RequestTemplates: '$default': '{"statusCode": 200, "messageId": $input.path(''$.messageId'')}' TimeoutInMillis: 29000 PayloadFormatVersion: '1.0'
ApiGatewayV2IntegrationResponseOnConnect: Type: AWS::ApiGatewayV2::IntegrationResponse Properties: ApiId: !Ref ApiGatewayV2Api IntegrationId: !Ref ApiGatewayV2IntegrationOnConnect IntegrationResponseKey: /200/
ApiGatewayV2IntegrationResponseOnMessage: Type: AWS::ApiGatewayV2::IntegrationResponse Properties: ApiId: !Ref ApiGatewayV2Api IntegrationId: !Ref ApiGatewayV2IntegrationOnMessage IntegrationResponseKey: /200/ ResponseTemplates: '1': '{"message": "Hello World"}' '2': '{"message": "Hi!"}' TemplateSelectionExpression: ${request.body.messageId}
Outputs: ApiGatewayV2ApiEndpoint: Value: !GetAtt ApiGatewayV2Api.ApiEndpoint次のコマンドで CloudFormation スタックをデプロイします。
aws cloudformation deploy \ --template-file template.yaml \ --stack-name api-gateway-websocket-with-mock-integration次のコマンドで、デプロイされた API Gateway のエンドポイントを取得します。
aws cloudformation describe-stacks \ --stack-name api-gateway-websocket-with-mock-integration \| jq ".Stacks[0].Outputs"出力例:
[ { "OutputKey": "ApiGatewayV2ApiEndpoint", "OutputValue": "wss://<id>.execute-api.<region>.amazonaws.com" }]テスト
WebSocket クライアントとして wscat をインストールします。
npm i wscat次のコマンドで WebSocket エンドポイントに接続します。新しい接続には $connect ルートが使われます。
wscat -c wss://<id>.execute-api.<region>.amazonaws.com/production/テストメッセージを送信し、messageId に応じたレスポンスを確認します。
> {"action": "message", "messageId": 1}< {"message": "Hello World"}> {"action": "message", "messageId": 2}< {"message": "Hi!"}クリーンアップ
次のコマンドで、この例で作成したすべての AWS リソースを削除します。
aws cloudformation delete-stack \ --stack-name api-gateway-websocket-with-mock-integrationまとめ
モック統合だけで API Gateway WebSocket API を構築し、バックエンドの Lambda をデプロイすることなく、受信した messageId に応じて異なるレスポンスを返せることを確認しました。
この例の「バックエンド」は、messageId をキーに選択するレスポンステンプレートだけで構成されています。そのため、実際のバックエンドを用意する前に WebSocket API のルーティングとレスポンス形式を試作する用途に適しています。$connect ルートと message ルートの動作を確かめるだけなら、Lambda 関数や永続化処理は不要です。
TemplateSelectionExpression では、リクエストやレスポンスの値からテンプレートを選択でき、選択した VTL テンプレートでペイロードを変換できます。ただし、モック統合からデータを永続化したり、別のサービスを呼び出したりすることはできません。そのような処理には、Lambda 統合、HTTP 統合、または AWS サービス統合を使用します。
Related posts
Lambda なしで API Gateway から SageMaker を呼び出す
API Gateway の AWS サービス統合から SageMaker 推論エンドポイントを呼び出し、Lambda プロキシを省略します。
Cognito User Pools と OIDC で Slack サインインを実装する
Cognito user pool を OIDC 経由で Slack と連携させ、"Sign in with Slack" を Amplify で Next.js アプリケーションに組み込みます。
Lambda Web Adapter で FastAPI を AWS Lambda にデプロイする
FastAPI で書いた API バックエンドをコンテナ化し、Lambda Web Adapter と AWS CDK を使って単一の Lambda 関数へデプロイします。
CloudFront 署名付き URL 経由で S3 にアップロードする
CloudFront の署名付き URL を使い、独自ドメイン経由で S3 にアップロードする方法を紹介します。S3 の署名付き URL を直接使えない場合に有用です。
AWS EventBridge Scheduler:スケジュールに沿って EC2 を起動・停止する
Lambda を介さず、EventBridge Scheduler から EC2 API を直接呼び出し、cron スケジュールに従って EC2 インスタンスを起動・停止します。
