Publish to an Amazon SNS topic using an Amazon SDK - Amazon Simple Notification Service
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Publish to an Amazon SNS topic using an Amazon SDK

The following code examples show how to publish messages to an Amazon SNS topic.

.NET
Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

  • For API details, see Publish in Amazon SDK for .NET API Reference.

C++
SDK for C++
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Aws::SDKOptions options; Aws::InitAPI(options); { Aws::SNS::SNSClient sns; Aws::String message = argv[1]; Aws::String topic_arn = argv[2]; Aws::SNS::Model::PublishRequest psms_req; psms_req.SetMessage(message); psms_req.SetTopicArn(topic_arn); auto psms_out = sns.Publish(psms_req); if (psms_out.IsSuccess()) { std::cout << "Message published successfully " << std::endl; } else { std::cout << "Error while publishing message " << psms_out.GetError().GetMessage() << std::endl; } } Aws::ShutdownAPI(options);
  • For API details, see Publish in Amazon SDK for C++ API Reference.

Go
SDK for Go V2
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

  • For API details, see Publish in Amazon SDK for Go API Reference.

Java
SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

public static void pubTopic(SnsClient snsClient, String message, String topicArn) { try { PublishRequest request = PublishRequest.builder() .message(message) .topicArn(topicArn) .build(); PublishResponse result = snsClient.publish(request); System.out.println(result.messageId() + " Message sent. Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • For API details, see Publish in Amazon SDK for Java 2.x API Reference.

JavaScript
SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Create the client in a separate module and export it.

import { SNSClient } from "@aws-sdk/client-sns"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SNS service object. const snsClient = new SNSClient({ region: REGION }); export { snsClient };

Import the SDK and client modules and call the API.

// Import required AWS SDK clients and commands for Node.js import {PublishCommand } from "@aws-sdk/client-sns"; import {snsClient } from "./libs/snsClient.js"; // Set the parameters var params = { Message: "MESSAGE_TEXT", // MESSAGE_TEXT TopicArn: "TOPIC_ARN", //TOPIC_ARN }; const run = async () => { try { const data = await snsClient.send(new PublishCommand(params)); console.log("Success.", data); return data; // For unit tests. } catch (err) { console.log("Error", err.stack); } }; run();
Kotlin
SDK for Kotlin
Note

This is prerelease documentation for a feature in preview release. It is subject to change.

Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

suspend fun pubTopic(topicArnVal: String, messageVal: String) { val request = PublishRequest { message = messageVal topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.publish(request) println("${result.messageId} message sent.") } }
  • For API details, see Publish in Amazon SDK for Kotlin API reference.

PHP
SDK for PHP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

require 'vendor/autoload.php'; use Aws\Sns\SnsClient; use Aws\Exception\AwsException; /** * Sends a message to an Amazon SNS topic. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $message = 'This message is sent from a Amazon SNS code sample.'; $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->publish([ 'Message' => $message, 'TopicArn' => $topic, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }
Python
SDK for Python (Boto3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Publish a message with attributes so that a subscription can filter based on attributes.

class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource def publish_message(topic, message, attributes): """ Publishes a message, with attributes, to a topic. Subscriptions can be filtered based on message attributes so that a subscription receives messages only when specified attributes are present. :param topic: The topic to publish to. :param message: The message to publish. :param attributes: The key-value attributes to attach to the message. Values must be either `str` or `bytes`. :return: The ID of the message. """ try: att_dict = {} for key, value in attributes.items(): if isinstance(value, str): att_dict[key] = {'DataType': 'String', 'StringValue': value} elif isinstance(value, bytes): att_dict[key] = {'DataType': 'Binary', 'BinaryValue': value} response = topic.publish(Message=message, MessageAttributes=att_dict) message_id = response['MessageId'] logger.info( "Published message with attributes %s to topic %s.", attributes, topic.arn) except ClientError: logger.exception("Couldn't publish message to topic %s.", topic.arn) raise else: return message_id

Publish a message that takes different forms based on the protocol of the subscriber.

class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource def publish_multi_message( topic, subject, default_message, sms_message, email_message): """ Publishes a multi-format message to a topic. A multi-format message takes different forms based on the protocol of the subscriber. For example, an SMS subscriber might receive a short, text-only version of the message while an email subscriber could receive an HTML version of the message. :param topic: The topic to publish to. :param subject: The subject of the message. :param default_message: The default version of the message. This version is sent to subscribers that have protocols that are not otherwise specified in the structured message. :param sms_message: The version of the message sent to SMS subscribers. :param email_message: The version of the message sent to email subscribers. :return: The ID of the message. """ try: message = { 'default': default_message, 'sms': sms_message, 'email': email_message } response = topic.publish( Message=json.dumps(message), Subject=subject, MessageStructure='json') message_id = response['MessageId'] logger.info("Published multi-format message to topic %s.", topic.arn) except ClientError: logger.exception("Couldn't publish message to topic %s.", topic.arn) raise else: return message_id
  • For API details, see Publish in Amazon SDK for Python (Boto3) API Reference.

Ruby
SDK for Ruby
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

require "aws-sdk-sns" # v2: require 'aws-sdk' def message_sent?(sns_client, topic_arn, message) sns_client.publish(topic_arn: topic_arn, message: message) rescue StandardError => e puts "Error while sending the message: #{e.message}" end def run_me topic_arn = "SNS_TOPIC_ARN" region = "REGION" message = "MESSAGE" # The text of the message to send. sns_client = Aws::SNS::Client.new(region: region) puts "Message sending." if message_sent?(sns_client, topic_arn, message) puts "The message was sent." else puts "The message was not sent. Stopping program." exit 1 end end run_me if $PROGRAM_NAME == __FILE__
Rust
SDK for Rust
Note

This documentation is for an SDK in preview release. The SDK is subject to change and should not be used in production.

Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

async fn subscribe_and_publish( client: &Client, topic_arn: &str, email_address: &str, ) -> Result<(), Error> { println!("Receiving on topic with ARN: `{}`", topic_arn); let rsp = client .subscribe() .topic_arn(topic_arn) .protocol("email") .endpoint(email_address) .send() .await?; println!("Added a subscription: {:?}", rsp); let rsp = client .publish() .topic_arn(topic_arn) .message("hello sns!") .send() .await?; println!("Published message: {:?}", rsp); Ok(()) }
  • For API details, see Publish in Amazon SDK for Rust API reference.

SAP ABAP
SDK for SAP ABAP
Note

This documentation is for an SDK in developer preview release. The SDK is subject to change and is not recommended for use in production.

Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

TRY. oo_result = lo_sns->publish( " oo_result is returned for testing purposes. " iv_topicarn = iv_topic_arn iv_message = iv_message ). MESSAGE 'Message published to SNS topic.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. ENDTRY.
  • For API details, see Publish in Amazon SDK for SAP ABAP API reference.

For a complete list of Amazon SDK developer guides and code examples, see Using Amazon SNS with an Amazon SDK. This topic also includes information about getting started and details about previous SDK versions.