Back
Engineering

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


Explore the SNS Topic component to visualize and represent SNS topics within your Amazon Web Services architecture. Discover

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:

<?php

require 'vendor/autoload.php';

use Aws\Sns\SnsClient;

$sns = SnsClient::createClient([
    'version' => '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<dyn std::error::error>> {
        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(())
    }
</dyn>

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

Related articles

Engineering

Unified Programmatic Access to Slack, Email, SMS, WhatsApp, Webhook and Other Messaging Channels

Streamline communication with unified programmatic access to Slack, Email, SMS, WhatsApp, and more. Simplify integration and messaging with expert solutions.

Engineering

Building a Real-Time Notification System for SaaS Applications with SuprSend

Discover how to implement a robust real-time notification system for SaaS applications using SuprSend. Explore technical strategies, advanced features, and integration examples for enhancing user engagement with seamless, personalized updates.

Engineering

What are Batch Notifications and Building in MongoDB, Django, Celery and Sendgrid

Discover how to design and implement a robust batched notification system using MongoDB, Django, Celery, and SendGrid. Learn key strategies for handling race conditions, ensuring single execution, managing retries, and implementing advanced features like item counting and user-specific batch windows.

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.