Amazon Web Services (AWS) - Publish a message to a Simple Notification Service (SNS) Topic using Python boto3

by
Jeremy Canfield |
Updated: October 21 2024
| Amazon Web Services (AWS) articles
This assumes you are familar with the basic configurations needed to connect to Amazon Web Services (AWS) using Python boto3. If not, check out my article Python (Scripting) - Getting Started with Amazon Web Services (AWS) boto3.
Here is the minimal boilerplate code without any error handling to publish a message to one of your Simple Notification Service (SNS) Topics.
#!/usr/bin/python3
import boto3
client = boto3.client('sns')
client.publish(
TopicArn='arn:aws:sns:us-east-1:123456789012:mytopic',
Subject='Hello',
Message='World'
)
Here is a more practical example, with try/except/else error handling.
#!/usr/bin/python3
import boto3
import sys
try:
client = boto3.client('sns')
except Exception as exception:
print(exception)
sys.exit(1)
try:
client.publish(
TopicArn='arn:aws:sns:us-east-1:123456789012:mytopic',
Subject='Hello',
Message='World'
)
except Exception as exception:
print(exception)
If you want to publish a JSON message, you would include MessageStructure='json' and the "default" must be the top-level JSON key.
#!/usr/bin/python3
import boto3
import json
import sys
try:
client = boto3.client('sns')
except Exception as exception:
print(exception)
sys.exit(1)
message = '{\"foo\" : \"hello\", \"bar\": \"world\"}'
try:
result = client.publish(
TopicArn='arn:aws:sns:us-east-1:123456789012:mytopic',
Subject='Hello',
MessageStructure='json',
Message=json.dumps({'default': json.dumps(message)})
)
except Exception as exception:
print(exception)
else:
print(f"result = {result}")
If exceptions are raised, the "result" dictionary should contain something like this.
{
'MessageId': '80dbc5ca-2dcb-59c3-8a8a-9ab96613dca7',
'ResponseMetadata': {
'RequestId': 'de7669d5-b8f5-59ee-bc60-36a6f32d1c8a',
'HTTPStatusCode': 200,
'HTTPHeaders': {
'x-amzn-requestid': 'de7669d5-b8f5-59ee-bc60-36a6f32d1c8a',
'date': 'Sun, 29 Sep 2024 12:35:36 GMT',
'content-type': 'text/xml',
'content-length': '294',
'connection': 'keep-alive'
},
'RetryAttempts': 0
}
}
Did you find this article helpful?
If so, consider buying me a coffee over at