bmoran
bmoran

Reputation: 1529

AWS: Publish SNS message for Lambda function via boto3 (Python2)

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)
)

Upvotes: 51

Views: 116354

Answers (3)

Kerem
Kerem

Reputation: 1553

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'
                        }
                    },
)

Upvotes: 5

Amir
Amir

Reputation: 6186

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'
)

Upvotes: 41

ryantuck
ryantuck

Reputation: 6674

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'
)

Upvotes: 111

Related Questions