Integrate SNS with WebSocket API Gateway


I would like to Publish messages to an SNS topic from a WebSocket API. I have a REST API working, but need a way to send a response back to the client, so figured I could use WebSocket. But, I can't figure out how to get the TopicArn and Message parameters into the sns query string. I have been trying CloudFormation configuration with:

  integration.request.querystring.Message: $request.body.msg
  integration.request.querystring.TopicArn: $request.body.topic

This generates Invalid mapping expression specified: $request.body.topic. Whatever I put on the right hand side triggers similar error. Is this possible? Ideally, I want to set the topic to a constant. Or, do I need to integrate with Lambda, and publish from there?

2 Answers

If you want to send notifications to the client, you will need to create a WebSockets API. The client will connect to the API, and you will need to record the connection ID for the users, usually, in a DynamoDB table. You do that from a Lambda function integrated with the $connect integration in the API.

When you want to send a message to the client, you will need to find the connection ID for the user, and use the API Gateway's postToConnection API to send the message to the client. If the message is coming from SNS, you will probably invoke a Lambda function that will get the message from SNS and send to API Gateway. You can't configure SNS to send the messages directly to the postToConnection API.

profile pictureAWS
answered 10 months ago
  • Thanks. I thought if I got this working I could figure out how to pass the connection ID along with the SNS message, and avoid the need for intervening Lambda. I only need the connection long enough to generate a single response from downstream of the SNS message.

  • In order to make a call to the postToConnection API you need to sign the request with AWS credentials that you get from an IAM Role. SNS doesn't know how to do it when making an HTTP request. When you invoke a Lambda function, with the appropriate IAM Role, the SDK that you use in the code, will sign the request going to API Gateway.


Hi, you can refer to ServerlessLand example here: This example covers how to use SNS with WebSocket API along with request validation

profile pictureAWS
answered 7 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions