Python AWS SNS

SNS topics, publishing notifications and managing subscriptions from Python services.

Zato lets you publish notifications through Amazon SNS directly from your Python services. You create an AWS connection in the Dashboard, and the SNS client is available under conn.sns - the same client that boto3.client('sns') returns, with credentials and configuration managed for you.

Publishing to a topic

# -*- coding: utf-8 -*-

# stdlib
import json

# Zato
from zato.server.service import Service

class NotifyOrderShipped(Service):

    input = 'order_id', 'topic_arn'

    def handle(self):

        # Get the connection by its Dashboard name
        conn = self.aws['My AWS']

        # Publish the notification
        message = json.dumps({'order_id': self.request.input.order_id, 'status': 'shipped'})

        response = conn.sns.publish(
            TopicArn=self.request.input.topic_arn,
            Subject='Order shipped',
            Message=message,
        )

        self.response.payload = {'message_id': response['MessageId']}

Creating topics

# -*- coding: utf-8 -*-

# Zato
from zato.server.service import Service

class CreateOrderTopic(Service):

    def handle(self):

        conn = self.aws['My AWS']

        # Create the topic - the call also succeeds if the topic already exists,
        # returning its ARN.
        response = conn.sns.create_topic(Name='order-events')

        self.response.payload = {'topic_arn': response['TopicArn']}

Managing subscriptions

# -*- coding: utf-8 -*-

# Zato
from zato.server.service import Service

class SubscribeQueueToTopic(Service):

    input = 'topic_arn', 'queue_arn'

    def handle(self):

        conn = self.aws['My AWS']

        # Deliver every notification from the topic to an SQS queue
        response = conn.sns.subscribe(
            TopicArn=self.request.input.topic_arn,
            Protocol='sqs',
            Endpoint=self.request.input.queue_arn,
        )

        self.response.payload = {'subscription_arn': response['SubscriptionArn']}

To see what is already subscribed, call conn.sns.list_subscriptions_by_topic(TopicArn=...), and to remove a subscription, call conn.sns.unsubscribe(SubscriptionArn=...).

More resources

Learn more