モックインテグレーションを使用した API Gateway WebSocket の構築

岩佐 孝浩
4 min read
API Gateway WebSocket Mock Integration
はじめに
URL Copied!
AWS ユーザーは API Gateway を使用して、モックインテグレーションを活用した WebSocket サーバー を迅速に構築できます。本チュートリアルでは、API Gateway WebSocket を設定してテストするための手順を説明します。
詳細なドキュメントについては、公式 AWS ガイド をご参照ください。
AWS リソースの作成
URL Copied!
以下の内容で CloudFormation テンプレートを作成します。
キーポイント
URL Copied!
messageId
は 68 行目 の$input.path('$.messageId')
を通じて渡されます。マッピングテンプレートリファレンス をご参照ください。- 77 行目と 84 行目 のインテグレーションレスポンスキーは AWS 公式ドキュメント に記載されている
statusCode
である必要があります。 - 85-87 行目 の
message
ルートのレスポンステンプレートは、messageId
値に基づいてレスポンスを変更します。
CloudFormation テンプレート
URL Copied!
AWSTemplateFormatVersion: 2010-09-09
Description: API Gateway WebSocket with Mock Integration
Resources:
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
スタックのデプロイ
URL Copied!
次のコマンドを使用して CloudFormation スタックをデプロイします。
aws cloudformation deploy \
--template-file template.yaml \
--stack-name api-gateway-websocket-with-mock-integration
出力値を取得するには、次のコマンドを使用します。
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"
}
]
テスト
URL Copied!
wscat をインストールして WebSocket クライアントとして使用します。
npm i wscat
WebSocket エンドポイントへの接続
URL Copied!
次のコマンドを実行して WebSocket エンドポイントに接続します。新しい接続には $connect
ルートが使用されます。
wscat -c wss://<id>.execute-api.<region>.amazonaws.com/production/
テストメッセージの送信
URL Copied!
テストメッセージを送信し、messageId
に基づいてレスポンスを観察します。
> {"action": "message", "messageId": 1}
< {"message": "Hello World"}
> {"action": "message", "messageId": 2}
< {"message": "Hi!"}
クリーンアップ
URL Copied!
次のコマンドを使用して、すべてのプロビジョニング済み AWS リソースを削除します。
aws cloudformation delete-stack --stack-name api-gateway-websocket-with-mock-integration
まとめ
URL Copied!
モックインテグレーション を使用することで、API Gateway WebSocket の設定が簡略化され、サーバーサイドの準備を待つことなく クライアントサイドの実装を可能にします。
楽しいコーディングを!🚀