python/cross_service/apigateway_websocket_chat/README.md
Shows how to use the AWS SDK for Python (Boto3) with Amazon API Gateway V2 to create a websocket API that integrates with AWS Lambda and Amazon DynamoDB.
You can create a similar API Gateway websocket chat application by using AWS Chalice. For a tutorial, see Chat Server Example.
Install prerequisites by running the following at a command prompt.
python -m pip install -r requirements.txt
This example requires AWS resources that can be deployed by the
AWS CloudFormation stack that is defined in the accompanying setup.yaml file.
This stack manages the following resources:
Deploy prerequisite resources by running the example script with the deploy flag at
a command prompt.
python websocket_chat.py deploy
Create and deploy the API Gateway websocket API by running with the demo flag at
a command prompt.
python websocket_chat.py demo
See an automated demo of how to use the Websockets package to connect and send
messages to the chat application by running with the chat flag at a command prompt.
python websocket_chat.py chat
Note: The Lambda handler for the chat application writes to an Amazon CloudWatch log. Checking this log can help you troubleshoot issues and give additional insight into the application.
Destroy example resources by running the script with the destroy flag at a command
prompt.
python websocket_chat.py destroy
The example contains the following files.
lambda_chat.py
Shows how to implement an AWS Lambda function as part of a websocket chat application. The function handles messages from an Amazon API Gateway websocket API and uses an Amazon DynamoDB table to track active connections by taking the following actions.
$connect request adds a connection ID and the associated user name to the
DynamoDB table.sendmessage request scans the table for connections and uses the API
Gateway Management API to post the message to all other connections.$disconnect request removes the connection record from the table.websocket_chat.py
Shows how to use API Gateway V2 to create a websocket API that is backed by a
Lambda function. The usage_demo and chat_demo scripts in this file show how to
accomplish the following actions.
setup.yaml
Contains a CloudFormation script that is used to create the resources needed for
the demo. Pass the deploy or destroy flag to the websocket_chat.py script to
create or remove these resources:
The setup.yaml file was built from the
AWS Cloud Development Kit (AWS CDK)
source script here:
/resources/cdk/python_example_code_apigateway_websocket/setup.ts.
The unit tests in this module use the botocore Stubber. The Stubber captures requests before they are sent to AWS, and returns a mocked response. To run all of the tests, run the following command in your [GitHub root]/python/example_code/apigateway/websocket folder.
python -m pytest
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0