In this tutorial, you'll create a serverless chat application with a WebSocket API. With a WebSocket API, you can support two-way communication between clients. Clients can receive messages without having to poll for updates.
This tutorial takes approximately 30 minutes to complete. First, you'll use an CloudFormation template to create Lambda functions that will handle API requests, as well as a DynamoDB table that stores your client IDs. Then, you'll use the API Gateway console to create a WebSocket API that integrates with your Lambda functions. Lastly, you'll test your API to verify that messages are sent and received.

To complete this tutorial, you need an AWS account and an AWS Identity and Access Management user with console access. For more information, seeSet up to use API Gateway.
You also needwscat to connect to your API. For more information, seeUse wscat to connect to a WebSocket API and send messages to it.
Download and unzipthe app creation template for CloudFormation. You'll use this template to create a Amazon DynamoDB table to store your app's client IDs. Each connected client has a unique ID which we will use as the table's partition key. This template also creates Lambda functions that update your client connections in DynamoDB and handle sending messages to connected clients.
Open the CloudFormation console athttps://console.aws.amazon.com/cloudformation.
ChooseCreate stack and then chooseWith new resources (standard).
ForSpecify template, chooseUpload a template file.
Select the template that you downloaded.
ChooseNext.
ForStack name, enterwebsocket-api-chat-app-tutorial and then chooseNext.
ForConfigure stack options, chooseNext.
ForCapabilities, acknowledge that CloudFormation can create IAM resources in your account.
ChooseNext, and then chooseSubmit.
CloudFormation provisions the resources specified in the template. It can take a few minutes to finish provisioning your resources. When the status of your CloudFormation stack isCREATE_COMPLETE, you're ready to move on to the next step.
You'll create a WebSocket API to handle client connections and route requests to the Lambda functions that you created in Step 1.
Sign in to the API Gateway console athttps://console.aws.amazon.com/apigateway.
ChooseCreate API. Then forWebSocket API, chooseBuild.
ForAPI name, enterwebsocket-chat-app-tutorial.
ForIP address type, selectIPv4.
ForRoute selection expression, enterrequest.body.action. The route selection expression determines the route that API Gateway invokes when a client sends a message.
ChooseNext.
ForPredefined routes, chooseAdd $connect,Add $disconnect, andAdd $default. The$connect and$disconnect routes are special routes that API Gateway invokes automatically when a client connects to or disconnects from an API. API Gateway invokes the$default route when no other routes match a request.
ForCustom routes, chooseAdd custom route. ForRoute key, entersendmessage. This custom route handles messages that are sent to connected clients.
ChooseNext.
UnderAttach integrations, for each route andIntegration type, choose Lambda.
ForLambda, choose the corresponding Lambda function that you created with CloudFormation in Step 1. Each function's name matches a route. For example, for the$connect route, choose the function namedwebsocket-chat-app-tutorial-ConnectHandler.
Review the stage that API Gateway creates for you. By default, API Gateway creates a stage nameproduction and automatically deploys your API to that stage. ChooseNext.
ChooseCreate and deploy.
Next, you'll test your API to make sure that it works correctly. Use thewscat command to connect to the API.
Sign in to the API Gateway console athttps://console.aws.amazon.com/apigateway.
Choose your API.
ChooseStages, and then chooseproduction.
Note your API'sWebSocket URL. The URL should look likewss://.abcdef123.execute-api.us-east-2.amazonaws.com/production
Use the following command to connect to your API. When you connect to your API, API Gateway invokes the$connect route. When this route is invoked, it calls a Lambda function that stores your connection ID in DynamoDB.
wscat -c wss://abcdef123.execute-api.us-west-2.amazonaws.com/productionConnected (press CTRL+C to quit)
Open a new terminal and run thewscat command again with the following parameters.
wscat -c wss://abcdef123.execute-api.us-west-2.amazonaws.com/productionConnected (press CTRL+C to quit)
This gives you two connected clients that can exchange messages.
API Gateway determines which route to invoke based on your API's route selection expression. Your API's route selection expression is$request.body.action. As a result, API Gateway invokes thesendmessage route when you send the following message:
{"action": "sendmessage", "message": "hello, everyone!"}The Lambda function associated with the invoked route collects the client IDs from DynamoDB. Then, the function calls the API Gateway Management API and sends the message to those clients. All connected clients receive the following message:
< hello, everyone!
API Gateway invokes your API's default route when a client sends a message that doesn't match your defined routes. The Lambda function associated with the$default route uses the API Gateway Management API to send the client information about their connection.
testUse the sendmessage route to send a message. Your info:{"ConnectedAt":"2022-01-25T18:50:04.673Z","Identity":{"SourceIp":"192.0.2.1","UserAgent":null},"LastActiveAt":"2022-01-25T18:50:07.642Z","connectionID":"Mg_ugfpqPHcCIVA="}
PressCTRL+C to disconnect from your API. When a client disconnects from your API, API Gateway invokes your API's$disconnect route. The Lambda integration for your API's$disconnect route removes the connection ID from DynamoDB.
To prevent unnecessary costs, delete the resources that you created as part of this tutorial. The following steps delete your CloudFormation stack and WebSocket API.
Sign in to the API Gateway console athttps://console.aws.amazon.com/apigateway.
On theAPIs page, select yourwebsocket-chat-app-tutorial API. ChooseActions, chooseDelete, and then confirm your choice.
Open the CloudFormation console athttps://console.aws.amazon.com/cloudformation.
Select your CloudFormation stack.
ChooseDelete and then confirm your choice.
You can automate the creation and cleanup of all of the AWS resources involved in this tutorial. For an CloudFormation template that creates this API and all related resources, seews-chat-app.yaml.