35
votes

I am trying to publish to an SNS topic which will then notify a Lambda function, as well as an SQS queue. My Lambda function does get called, but the CloudWatch logs state that my "event" object is None. The boto3 docs states to use the kwarg MessageStructure='json' but that throws a ClientError.

Hopefully I've supplied enough information.

Example Code:

import json
import boto3

message = {"foo": "bar"}
client = boto3.client('sns')
response = client.publish(
    TargetArn=arn,
    Message=json.dumps(message)
)
3
You only need the MessageStructure param if you are trying to send different messages to different types of subscribers (e.g. email vs. SMS). Could you include the code for your Lambda function? I'm assuming that the code shown above works without any errors, right?garnaat
If you're running this using the Python SDK on say an EC2-Instance don't forget to add a region inside the client e.g., client = boto3.client('sns', region_name='us-east-1') bradmontgomery.net/blog/…Kyle Bridenstine

3 Answers

87
votes

you need to add a default key to your message payload, and specify MessageStructure:

import json
import boto3

message = {"foo": "bar"}
client = boto3.client('sns')
response = client.publish(
    TargetArn=arn,
    Message=json.dumps({'default': json.dumps(message)}),
    MessageStructure='json'
)
32
votes

Just in case you want to have different messages for sms and email subscribers:

import json
import boto3

message = {"foo": "bar"}
client = boto3.client('sns')
response = client.publish(
    TargetArn=arn,
    Message=json.dumps({'default': json.dumps(message),
                        'sms': 'here a short version of the message',
                        'email': 'here a longer version of the message'}),
    Subject='a short subject for your message',
    MessageStructure='json'
)
0
votes

In case you are publishing your message with a filter policy, you should also use MessageAttributes parameter to add your SNS filter.

To invoke your Lambda with this SNS subscription filter policy {"endpoint": ["distance"]}:

import json
import boto3

message = {"foo": "bar"}
client = boto3.client('sns')
response = client.publish(
    TargetArn=arn,
    Message=json.dumps({'default': json.dumps(message)}),
    MessageStructure='json',
    MessageAttributes={
                        'foo': {
                            'DataType': 'String',
                            'StringValue': 'bar'
                        }
                    },
)