API Gateway WebSocket:モック統合の実装

API Gateway WebSocket:モック統合の実装

バックエンドの Lambda を使わず、モック統合のみで API Gateway WebSocket API を構築し、あらかじめ用意したレスポンスを返します。

Takahiro Iwasa
4 min read

API Gateway のモック統合を使うと、バックエンドを用意せずに、あらかじめ定義した WebSocket レスポンスを返せます。実際のビジネスロジックを実装する前に、ルーティングやレスポンス形式を検証する用途に便利です。

Integrations for WebSocket APIs in API Gateway

構築

template.yaml
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

次のコマンドで CloudFormation スタックをデプロイします。

Terminal window
aws cloudformation deploy \
--template-file template.yaml \
--stack-name api-gateway-websocket-with-mock-integration

次のコマンドで、デプロイされた API Gateway のエンドポイントを取得します。

Terminal window
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 をインストールします。

Terminal window
npm i wscat

次のコマンドで WebSocket エンドポイントに接続します。新しい接続には $connect ルートが使われます。

Terminal window
wscat -c wss://<id>.execute-api.<region>.amazonaws.com/production/

テストメッセージを送信し、messageId に応じたレスポンスを確認します。

Terminal window
> {"action": "message", "messageId": 1}
< {"message": "Hello World"}
> {"action": "message", "messageId": 2}
< {"message": "Hi!"}

クリーンアップ

次のコマンドで、この例で作成したすべての AWS リソースを削除します。

Terminal window
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 サービス統合を使用します。

About the author

Takahiro Iwasa

Takahiro Iwasa

Software Developer

This blog shares technical notes from hands-on projects—architecture, implementation, and AWS service integrations.