An Amazon SNS topic is a logical access point that acts as a communication channel. A topic lets you group multiple endpoints (such as AWS Lambda, Amazon SQS, HTTP/S, or an email address).
To broadcast the messages of a message-producer system (for example, an e-commerce website) working with multiple other services that require its messages (for example, checkout and fulfillment systems), you can create a topic for your producer system.
The first and most common Amazon SNS task is creating a topic. This page shows how you can use the AWS Management Console, the AWS SDK for Java, and the AWS SDK for .NET to create a topic.
During creation, you choose a topic type (standard or FIFO) and name the topic. After creating a topic, you can't change the topic type or name. All other configuration choices are optional during topic creation, and you can edit them later.
ImportantDo not add personally identifiable information (PII) or other confidential or sensitive information in topic names. Topic names are accessible to other Amazon Web Services, including CloudWatch Logs. Topic names are not intended to be used for private or sensitive data.
To create a topic using the AWS Management ConsoleCreating a topic in Amazon SNS establishes the foundation for message distribution, enabling you to publish messages that can be fanned out to multiple subscribers. This step is essential to configure the topic's type, encryption settings, and access policies, ensuring the topic meets the organizationâs security, compliance, and operational requirements.
Sign in to the Amazon SNS console.
Do one of the following:
If no topics have ever been created under your AWS account before, read the description of Amazon SNS on the home page.
If topics have been created under your AWS account before, on the navigation panel, choose Topics.
On the Topics page, choose Create topic.
On the Create topic page, in the Details section, do the following:
For Type, choose a topic type (Standard or FIFO).
Enter a Name for the topic. For a FIFO topic, add .fifo to the end of the name.
(Optional) Enter a Display name for the topic.
ImportantWhen subscribing to an email endpoint, the combined character count for the Amazon SNS topic display name and the sending email address (for example, no-reply@sns.amazonaws.com) must not exceed 320 UTF-8 characters. You can use a third party encoding tool to verify the length of the sending address before configuring a display name for your Amazon SNS topic.
(Optional) For a FIFO topic, you can choose content-based message deduplication to enable default message deduplication. For more information, see Amazon SNS message deduplication for FIFO topics.
(Optional) Expand the Encryption section and do the following. For more information, see Securing Amazon SNS data with server-side encryption.
Choose Enable encryption.
Specify the AWS KMS key. For more information, see Key terms.
For each KMS type, the Description, Account, and KMS ARN are displayed.
ImportantIf you aren't the owner of the KMS, or if you log in with an account that doesn't have the kms:ListAliases
and kms:DescribeKey
permissions, you won't be able to view information about the KMS on the Amazon SNS console.
Ask the owner of the KMS to grant you these permissions. For more information, see the AWS KMS API Permissions: Actions and Resources Reference in the AWS Key Management Service Developer Guide.
The AWS managed KMS for Amazon SNS (Default) alias/aws/sns is selected by default.
NoteKeep the following in mind:
The first time you use the AWS Management Console to specify the AWS managed KMS for Amazon SNS for a topic, AWS KMS creates the AWS managed KMS for Amazon SNS.
Alternatively, the first time you use the Publish
action on a topic with SSE enabled, AWS KMS creates the AWS managed KMS for Amazon SNS.
To use a custom KMS from your AWS account, choose the KMS key field and then choose the custom KMS from the list.
NoteFor instructions on creating custom KMSs, see Creating Keys in the AWS Key Management Service Developer Guide
To use a custom KMS ARN from your AWS account or from another AWS account, enter it into the KMS key field.
(Optional) By default, only the topic owner can publish or subscribe to the topic. To configure additional access permissions, expand the Access policy section. For more information, see Identity and access management in Amazon SNS and Example cases for Amazon SNS access control.
NoteWhen you create a topic using the console, the default policy uses the aws:SourceOwner
condition key. This key is similar to aws:SourceAccount
.
(Optional) To configure how Amazon SNS retries failed message delivery attempts, expand the Delivery retry policy (HTTP/S) section. For more information, see Amazon SNS message delivery retries.
(Optional) To configure how Amazon SNS logs the delivery of messages to CloudWatch, expand the Delivery status logging section. For more information, see Amazon SNS message delivery status.
(Optional) To add metadata tags to the topic, expand the Tags section, enter a Key and a Value (optional) and choose Add tag. For more information, see Amazon SNS topic tagging.
Choose Create topic.
The topic is created and the MyTopic
page is displayed.
The topic's Name, ARN, (optional) Display name, and Topic owner's AWS account ID are displayed in the Details section.
Copy the topic ARN to the clipboard, for example:
arn:aws:sns:us-east-2:123456789012:MyTopic
To use an AWS SDK, you must configure it with your credentials. For more information, see The shared config and credentials files in the AWS SDKs and Tools Reference Guide.
The following code examples show how to use CreateTopic
.
Create a topic with a specific name.
using System;
using System.Threading.Tasks;
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;
/// <summary>
/// This example shows how to use Amazon Simple Notification Service
/// (Amazon SNS) to add a new Amazon SNS topic.
/// </summary>
public class CreateSNSTopic
{
public static async Task Main()
{
string topicName = "ExampleSNSTopic";
IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient();
var topicArn = await CreateSNSTopicAsync(client, topicName);
Console.WriteLine($"New topic ARN: {topicArn}");
}
/// <summary>
/// Creates a new SNS topic using the supplied topic name.
/// </summary>
/// <param name="client">The initialized SNS client object used to
/// create the new topic.</param>
/// <param name="topicName">A string representing the topic name.</param>
/// <returns>The Amazon Resource Name (ARN) of the created topic.</returns>
public static async Task<string> CreateSNSTopicAsync(IAmazonSimpleNotificationService client, string topicName)
{
var request = new CreateTopicRequest
{
Name = topicName,
};
var response = await client.CreateTopicAsync(request);
return response.TopicArn;
}
}
Create a new topic with a name and specific FIFO and de-duplication attributes.
/// <summary>
/// Create a new topic with a name and specific FIFO and de-duplication attributes.
/// </summary>
/// <param name="topicName">The name for the topic.</param>
/// <param name="useFifoTopic">True to use a FIFO topic.</param>
/// <param name="useContentBasedDeduplication">True to use content-based de-duplication.</param>
/// <returns>The ARN of the new topic.</returns>
public async Task<string> CreateTopicWithName(string topicName, bool useFifoTopic, bool useContentBasedDeduplication)
{
var createTopicRequest = new CreateTopicRequest()
{
Name = topicName,
};
if (useFifoTopic)
{
// Update the name if it is not correct for a FIFO topic.
if (!topicName.EndsWith(".fifo"))
{
createTopicRequest.Name = topicName + ".fifo";
}
// Add the attributes from the method parameters.
createTopicRequest.Attributes = new Dictionary<string, string>
{
{ "FifoTopic", "true" }
};
if (useContentBasedDeduplication)
{
createTopicRequest.Attributes.Add("ContentBasedDeduplication", "true");
}
}
var createResponse = await _amazonSNSClient.CreateTopicAsync(createTopicRequest);
return createResponse.TopicArn;
}
For API details, see CreateTopic in AWS SDK for .NET API Reference.
//! Create an Amazon Simple Notification Service (Amazon SNS) topic.
/*!
\param topicName: An Amazon SNS topic name.
\param topicARNResult: String to return the Amazon Resource Name (ARN) for the topic.
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool AwsDoc::SNS::createTopic(const Aws::String &topicName,
Aws::String &topicARNResult,
const Aws::Client::ClientConfiguration &clientConfiguration) {
Aws::SNS::SNSClient snsClient(clientConfiguration);
Aws::SNS::Model::CreateTopicRequest request;
request.SetName(topicName);
const Aws::SNS::Model::CreateTopicOutcome outcome = snsClient.CreateTopic(request);
if (outcome.IsSuccess()) {
topicARNResult = outcome.GetResult().GetTopicArn();
std::cout << "Successfully created an Amazon SNS topic " << topicName
<< " with topic ARN '" << topicARNResult
<< "'." << std::endl;
}
else {
std::cerr << "Error creating topic " << topicName << ":" <<
outcome.GetError().GetMessage() << std::endl;
topicARNResult.clear();
}
return outcome.IsSuccess();
}
For API details, see CreateTopic in AWS SDK for C++ API Reference.
To create an SNS topic
The following create-topic
example creates an SNS topic named my-topic
.
aws sns create-topic \
--name my-topic
Output:
{
"ResponseMetadata": {
"RequestId": "1469e8d7-1642-564e-b85d-a19b4b341f83"
},
"TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic"
}
For more information, see Using the AWS Command Line Interface with Amazon SQS and Amazon SNS in the AWS Command Line Interface User Guide.
For API details, see CreateTopic in AWS CLI Command Reference.
import (
"context"
"encoding/json"
"log"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/sns"
"github.com/aws/aws-sdk-go-v2/service/sns/types"
)
// SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions
// used in the examples.
type SnsActions struct {
SnsClient *sns.Client
}
// CreateTopic creates an Amazon SNS topic with the specified name. You can optionally
// specify that the topic is created as a FIFO topic and whether it uses content-based
// deduplication instead of ID-based deduplication.
func (actor SnsActions) CreateTopic(ctx context.Context, topicName string, isFifoTopic bool, contentBasedDeduplication bool) (string, error) {
var topicArn string
topicAttributes := map[string]string{}
if isFifoTopic {
topicAttributes["FifoTopic"] = "true"
}
if contentBasedDeduplication {
topicAttributes["ContentBasedDeduplication"] = "true"
}
topic, err := actor.SnsClient.CreateTopic(ctx, &sns.CreateTopicInput{
Name: aws.String(topicName),
Attributes: topicAttributes,
})
if err != nil {
log.Printf("Couldn't create topic %v. Here's why: %v\n", topicName, err)
} else {
topicArn = *topic.TopicArn
}
return topicArn, err
}
For API details, see CreateTopic in AWS SDK for Go API Reference.
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.CreateTopicRequest;
import software.amazon.awssdk.services.sns.model.CreateTopicResponse;
import software.amazon.awssdk.services.sns.model.SnsException;
/**
* Before running this Java V2 code example, set up your development
* environment, including your credentials.
*
* For more information, see the following documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*/
public class CreateTopic {
public static void main(String[] args) {
final String usage = """
Usage: <topicName>
Where:
topicName - The name of the topic to create (for example, mytopic).
""";
if (args.length != 1) {
System.out.println(usage);
System.exit(1);
}
String topicName = args[0];
System.out.println("Creating a topic with name: " + topicName);
SnsClient snsClient = SnsClient.builder()
.region(Region.US_EAST_1)
.build();
String arnVal = createSNSTopic(snsClient, topicName);
System.out.println("The topic ARN is" + arnVal);
snsClient.close();
}
public static String createSNSTopic(SnsClient snsClient, String topicName) {
CreateTopicResponse result;
try {
CreateTopicRequest request = CreateTopicRequest.builder()
.name(topicName)
.build();
result = snsClient.createTopic(request);
return result.topicArn();
} catch (SnsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return "";
}
}
For API details, see CreateTopic in AWS SDK for Java 2.x API Reference.
Create the client in a separate module and export it.
import { SNSClient } from "@aws-sdk/client-sns";
// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
Import the SDK and client modules and call the API.
import { CreateTopicCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";
/**
* @param {string} topicName - The name of the topic to create.
*/
export const createTopic = async (topicName = "TOPIC_NAME") => {
const response = await snsClient.send(
new CreateTopicCommand({ Name: topicName }),
);
console.log(response);
// {
// '$metadata': {
// httpStatusCode: 200,
// requestId: '087b8ad2-4593-50c4-a496-d7e90b82cf3e',
// extendedRequestId: undefined,
// cfId: undefined,
// attempts: 1,
// totalRetryDelay: 0
// },
// TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME'
// }
return response;
};
suspend fun createSNSTopic(topicName: String): String {
val request =
CreateTopicRequest {
name = topicName
}
SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
val result = snsClient.createTopic(request)
return result.topicArn.toString()
}
}
For API details, see CreateTopic in AWS SDK for Kotlin API reference.
require 'vendor/autoload.php';
use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;
/**
* Create a Simple Notification Service topics in your AWS account at the requested region.
*
* 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'
]);
$topicname = 'myTopic';
try {
$result = $SnSclient->createTopic([
'Name' => $topicname,
]);
var_dump($result);
} catch (AwsException $e) {
// output error message if fails
error_log($e->getMessage());
}
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 create_topic(self, name):
"""
Creates a notification topic.
:param name: The name of the topic to create.
:return: The newly created topic.
"""
try:
topic = self.sns_resource.create_topic(Name=name)
logger.info("Created topic %s with ARN %s.", name, topic.arn)
except ClientError:
logger.exception("Couldn't create topic %s.", name)
raise
else:
return topic
For API details, see CreateTopic in AWS SDK for Python (Boto3) API Reference.
# This class demonstrates how to create an Amazon Simple Notification Service (SNS) topic.
class SNSTopicCreator
# Initializes an SNS client.
#
# Utilizes the default AWS configuration for region and credentials.
def initialize
@sns_client = Aws::SNS::Client.new
end
# Attempts to create an SNS topic with the specified name.
#
# @param topic_name [String] The name of the SNS topic to create.
# @return [Boolean] true if the topic was successfully created, false otherwise.
def create_topic(topic_name)
@sns_client.create_topic(name: topic_name)
puts "The topic '#{topic_name}' was successfully created."
true
rescue Aws::SNS::Errors::ServiceError => e
# Handles SNS service errors gracefully.
puts "Error while creating the topic named '#{topic_name}': #{e.message}"
false
end
end
# Example usage:
if $PROGRAM_NAME == __FILE__
topic_name = 'YourTopicName' # Replace with your topic name
sns_topic_creator = SNSTopicCreator.new
puts "Creating the topic '#{topic_name}'..."
unless sns_topic_creator.create_topic(topic_name)
puts 'The topic was not created. Stopping program.'
exit 1
end
end
async fn make_topic(client: &Client, topic_name: &str) -> Result<(), Error> {
let resp = client.create_topic().name(topic_name).send().await?;
println!(
"Created topic with ARN: {}",
resp.topic_arn().unwrap_or_default()
);
Ok(())
}
For API details, see CreateTopic in AWS SDK for Rust API reference.
TRY.
oo_result = lo_sns->createtopic( iv_name = iv_topic_name ). " oo_result is returned for testing purposes. "
MESSAGE 'SNS topic created' TYPE 'I'.
CATCH /aws1/cx_snstopiclimitexcdex.
MESSAGE 'Unable to create more topics. You have reached the maximum number of topics allowed.' TYPE 'E'.
ENDTRY.
For API details, see CreateTopic in AWS SDK for SAP ABAP API reference.
import AWSSNS
let config = try await SNSClient.SNSClientConfiguration(region: region)
let snsClient = SNSClient(config: config)
let output = try await snsClient.createTopic(
input: CreateTopicInput(name: name)
)
guard let arn = output.topicArn else {
print("No topic ARN returned by Amazon SNS.")
return
}
For API details, see CreateTopic in AWS SDK for Swift API reference.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4