Engineering

Creating Amazon SNS Topics using AWS SDK in 10+ Languages Including Java, .NET, Python, and Go

Sanjeev Kumar
June 2, 2024
Explore the SNS Topic component to visualize and represent SNS topics within your Amazon Web Services architecture. Discover
TABLE OF CONTENTS

Creating SNS Topics

To create an Amazon SNS topic, follow these steps:

  1. Sign in to the AWS Management Console:
    • Go to the AWS Management Console and sign in with your AWS account credentials.
    • Navigate to the Amazon SNS dashboard.
  2. Create a Topic:
    • Click on Topics in the navigation panel.
    • Click on Create topic.
    • Choose the topic type:
      • Standard: This is the default topic type and supports multiple subscriber types.
      • FIFO (First-In-First-Out): This topic type ensures that messages are processed in the order they are received.
  3. Configure the Topic:
    • Enter a Name for the topic. For a FIFO topic, add .fifo to the end of the name.
    • Optionally, enter a Display name for the topic.
    • For a FIFO topic, you can choose Content-based message deduplication to enable default message deduplication.
    • Expand the Encryption section and choose Enable encryption to specify the AWS KMS key.
  4. Create the Topic:
    • Click Create topic to create the topic.

Example of Creating an SNS Topic using the AWS Management Console

Here is an example of creating an SNS topic using the AWS Management Console:

  1. Sign in to the AWS Management Console.
  2. Navigate to the Amazon SNS dashboard.
  3. Click on Topics in the navigation panel.
  4. Click on Create topic.
  5. Choose Standard as the topic type.
  6. Enter Events as the topic name.
  7. Optionally, enter Events Display as the display name.
  8. Expand the Encryption section and choose Enable encryption.
  9. Specify the AWS KMS key.
  10. Click Create topic to create the topic.

Example of Creating an SNS Topic using the AWS SDK for Java

Here is an example of creating an SNS topic using the AWS SDK for Java:

 
    import software.amazon.awssdk.services.sns.SnsClient;
    import software.amazon.awssdk.services.sns.model.CreateTopicRequest;
    import software.amazon.awssdk.services.sns.model.CreateTopicResponse;

    public class CreateSnsTopic {
        public static void main(String[] args) {
            SnsClient snsClient = SnsClient.create();

            CreateTopicRequest request = CreateTopicRequest.builder()
                    .name("Events")
                    .build();

            CreateTopicResponse response = snsClient.createTopic(request);

            System.out.println("Topic ARN: " + response.topicArn());
        }
    }

    

Example of Creating an SNS Topic using the AWS SDK for .NET

Here is an example of creating an SNS topic using the AWS SDK for .NET:

 
    using Amazon.SNS;
    using Amazon.SNS.Model;

    public class CreateSnsTopic
    {
        public static void Main(string[] args)
        {
            AmazonSNSClient snsClient = new AmazonSNSClient("accessKey", "secretKey", Amazon.Region.USWest2);

            CreateTopicRequest request = new CreateTopicRequest
            {
                Name = "Events"
            };

            CreateTopicResponse response = snsClient.CreateTopic(request);

            Console.WriteLine("Topic ARN: " + response.TopicArn);
        }
    }

    

Example of Creating an SNS Topic using the AWS CLI

Here is an example of creating an SNS topic using the AWS CLI:

 
		aws sns create-topic --name Events

    

Example of Creating an SNS Topic using the AWS SDK for Python

Here is an example of creating an SNS topic using the AWS SDK for Python:

 
    import boto3

    sns = boto3.client('sns')

    response = sns.create_topic(Name='Events')

    print("Topic ARN: " + response['TopicArn'])

    

Example of Creating an SNS Topic using the AWS SDK for Go

Here is an example of creating an SNS topic using the AWS SDK for Go:

 
    package main

    import (
      "context"
      "fmt"

      "github.com/aws/aws-sdk-go/aws"
      "github.com/aws/aws-sdk-go/aws/session"
      "github.com/aws/aws-sdk-go/service/sns"
    )

    func main() {
      sess, err := session.NewSession(&aws.Config{Region: aws.String("us-west-2")}, nil)
      if err != nil {
        fmt.Println(err)
        return
      }

      snsSvc := sns.New(sess)

      input := &sns.CreateTopicInput{
        Name: aws.String("Events"),
      }

      result, err := snsSvc.CreateTopic(context.TODO(), input)
      if err != nil {
        fmt.Println(err)
        return
      }

      fmt.Println("Topic ARN: " + *result.TopicArn)
    }

    

Example of Creating an SNS Topic using the AWS SDK for Node.js

Here is an example of creating an SNS topic using the AWS SDK for Node.js:

 
    const AWS = require('aws-sdk');
    const sns = new AWS.SNS({ region: 'us-west-2' });

    const params = {
      Name: 'Events',
    };

    sns.createTopic(params, (err, data) => {
      if (err) {
        console.log(err);
      } else {
        console.log("Topic ARN: " + data.TopicArn);
      }
    });

    

Example of Creating an SNS Topic using the AWS SDK for Ruby

Here is an example of creating an SNS topic using the AWS SDK for Ruby:

 
    require 'aws-sdk'

    sns = Aws::SNS::Client.new(region: 'us-west-2')

    params = {
      name: 'Events',
    }

    response = sns.create_topic(params)

    puts "Topic ARN: #{response.topic_arn}"

    

Example of Creating an SNS Topic using the AWS SDK for PHP

Here is an example of creating an SNS topic using the AWS SDK for PHP:

 
     'latest',
        'region'  => 'us-west-2',
    ]);

    $params = [
        'Name' => 'Events',
    ];

    $response = $sns->createTopic($params);

    echo "Topic ARN: " . $response['TopicArn'] . "\n";

    

Example of Creating an SNS Topic using the AWS SDK for Swift

Here is an example of creating an SNS topic using the AWS SDK for Swift:

 
    import AWSSDK

    let sns = SNSClient(region: .usWest2)

    let params = SNSCreateTopicInput(name: "Events")

    sns.createTopic(params) { (result, error) in
        if let error = error {
            print("Error: \(error)")
        } else {
            print("Topic ARN: \(result?.topicArn ?? "")")
        }
    }

    

Example of Creating an SNS Topic using the AWS SDK for Rust

Here is an example of creating an SNS topic using the AWS SDK for Rust:

 
    use aws_sdk_sns::{Client, CreateTopicRequest};

    async fn main() -> Result<(), Box> {
        let sns = Client::new().await?;

        let params = CreateTopicRequest {
            name: Some("Events".to_string()),
            ..Default::default()
        };

        let result = sns.create_topic(params).await?;

        println!("Topic ARN: {}", result.topic_arn);

        Ok(())
    }

    

Example of Creating an SNS Topic using the AWS SDK for Kotlin

Here is an example of creating an SNS topic using the AWS SDK for Kotlin:

 
    import software.amazon.awssdk.services.sns.SnsClient
    import software.amazon.awssdk.services.sns.model.CreateTopicRequest
    import software.amazon.awssdk.services.sns.model.CreateTopicResponse

    fun main() {
        val sns = SnsClient.create()

        val request = CreateTopicRequest.builder()
            .name("Events")
            .build()

        val response = sns.createTopic(request)

        println("Topic ARN: ${response.topicArn()}")
    }

    

Example of Creating an SNS Topic using the AWS SDK for Scala

Here is an example of creating an SNS topic using the AWS SDK for Scala:

 
    import software.amazon.awssdk.services.sns.SnsClient
    import software.amazon.awssdk.services.sns.model.CreateTopicRequest
    import software.amazon.awssdk.services.sns.model.CreateTopicResponse

    object CreateSnsTopic {
      def main(args: Array[String]): Unit = {
        val sns = SnsClient.create()

        val request = CreateTopicRequest.builder()
          .name("Events")
          .build()

        val response = sns.createTopic(request)

        println(s"Topic ARN: ${response.topicArn()}")
      }
    }

    

Example of Creating an SNS Topic using the AWS SDK for TypeScript

Here is an example of creating an SNS topic using the AWS SDK for TypeScript:

 
    import * as AWS from 'aws-sdk';
    import * as sns from 'aws-sdk/clients/sns';

    const snsClient = new sns({ region: 'us-west-2' });

    const params = {
      Name: 'Events',
    };

    snsClient.createTopic(params, (err, data) => {
      if (err) {
        console.log(err);
      } else {
        console.log(`Topic ARN: ${data.TopicArn}`);
      }
    });

    

Example of Creating an SNS Topic using the AWS SDK for Dart

Here is an example of creating an SNS topic using the AWS SDK for Dart:

 
    import 'package:aws_sdk_sns/sns.dart';

    void main() async {
      final sns = SnsClient(region: 'us-west-2');

      final params = CreateTopicRequest(name: 'Events');

      final response = await sns.createTopic(params);

      print('Topic ARN: ${response.topicArn}');
    }

    

Written by:
Sanjeev Kumar
Engineering, SuprSend
Get a powerful notification engine with SuprSend
Build smart notifications across channels in minutes with a single API and frontend components
Implement a powerful stack for your notifications
By clicking “Accept All Cookies”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. View our Privacy Policy for more information.