using localstack AWS how can i listen to SNS event in chalice

865 views Asked by At

i have a localstack setup and i can succesfuly publish SNS from my chalice application by poiting the endpoint url like such

_sns_topic = session.resource('sns', endpoint_url='http://localhost:4566')

however one of our endpoints needs to listen to this SNS event in local, but it is currently set-up using @app.on_sns_message()

@app.on_sns_message(topic='topicNameHere', ''))
def onSnsEvent(event) -> None:
   #do something

I checked the documentation but i cant seem to find how can I point this so that it will listen to local/localstack events instead.

any tips and/or idea?

1

There are 1 answers

0
Harsh Mishra On BEST ANSWER

I was able to get this running on my side by following the official Chalice docs and using LocalStack's recommended Chalice wrapper. Here are the steps:

  • Start LocalStack: localstack start -d
  • Create a SNS topic: awslocal sns create-topic --name my-demo-topic --region us-east-1 --output table | cat (I am using my-demo-topic).
  • Install chalice-local: pip3 install chalice-local.
  • Initiate a new app: chalice-local new-project chalice-demo-sns
  • Keep the following code inside chalice-demo-sns:
from chalice import Chalice

app = Chalice(app_name='chalice-sns-demo')
app.debug = True

@app.on_sns_message(topic='my-demo-topic')
def handle_sns_message(event):
    app.log.debug("Received message with subject: %s, message: %s",
                  event.subject, event.message)
  • Deploy it: chalice-local deploy
  • Use boto3 to publish messages on SNS:
$ python
>>> import boto3
>>> endpoint_url = "http://localhost.localstack.cloud:4566"
>>> sns = boto3.client('sns', endpoint_url=endpoint_url)
>>> topic_arn = [t['TopicArn'] for t in sns.list_topics()['Topics']
...              if t['TopicArn'].endswith(':my-demo-topic')][0]
>>> sns.publish(Message='TestMessage1', Subject='TestSubject1',
...             TopicArn=topic_arn)
{'MessageId': '12345', 'ResponseMetadata': {}}
>>> sns.publish(Message='TestMessage2', Subject='TestSubject2',
...             TopicArn=topic_arn)
{'MessageId': '54321', 'ResponseMetadata': {}}
  • Check the logs: chalice-local logs -n handle_sns_message