Integrate SNS with WebSocket API Gateway

0

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:

RequestParameters:
  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 回答
1

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
专家
Uri
已回答 1 年前
  • 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.

0

Hi, you can refer to ServerlessLand example here: https://serverlessland.com/patterns/apigw-websocket-api-sns This example covers how to use SNS with WebSocket API along with request validation

profile pictureAWS
支持工程师
Bharat
已回答 9 个月前

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则