HomeServerlessMessaging and QueuingAPI/CLI
Using Go, Python or NodeJS with SNS
Jump toUpdate content

Using Go, Python or NodeJS with SNS

Reviewed on 10 July 2023 • Published on 04 January 2023

AWS provides a number of Software Development Kits (SDKs) which provide language-specific APIs for AWS services, including SNS.

This page provides code samples to show you how to get started using these SDKs with your Scaleway Messaging SQS/SNS namespace, more specifically with SNS.

Security & Identity (IAM):

You may need certain IAM permissions to carry out some actions described on this page. This means:

  • you are the Owner of the Scaleway Organization in which the actions will be carried out, or
  • you are an IAM user of the Organization, with a policy granting you the necessary permission sets
Requirements:

Go

Connect to SNS (Go)

The following code shows you how to connect to SNS:

import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sns"
)
func main() {
awsSession := session.Must(session.NewSession(&aws.Config{
Region: aws.String("fr-par"),
Endpoint: aws.String("http://sns-sns.mnq.fr-par.scw.cloud"),
Credentials: credentials.NewStaticCredentials(AwsAccessKey, AwsSecretKey, ""),
}))
awsSns := sns.New(awsSession)
[...]
}
Note:

The Endpoint for Scaleway Messaging and Queuing is https://sqs-sns.mnq.fr-par.scw.cloud. The values for the access and secret keys should be the credentials you generated for your SQS/SNS namespace.

Once connected to the SNS service, you can use any of the SDK’s available functions. Be aware though that some functions are not supported by Scaleway Messaging and Queuing, so make sure to check the link for more details on these. See the official SDK documentation for more information on getting started with the SDK, or keep reading for some code examples.

Create topic (Go)

createTopicResponse, _ := awsSNS.CreateTopic(&sns.CreateTopicInput{
Name: aws.String("my-test-topic"),
})
fmt.Println(*createTopicResponse.TopicArn)

Publish messages to this topic (Go)

Be careful: messages sent to topics with no subscriptions are automatically deleted

for i := 0; i < 10; i++ {
_, _ = awsSNS.Publish(&sns.PublishInput{
Message: aws.String(fmt.Sprintf("Hello World: %d", i)),
TopicArn: createTopicResponse.TopicArn,
})
}

Create subscriptions to this topic (Go)

Subscribe to an SQS queue from the same namespace

_, _ = awsSns.Subscribe(&sns.SubscribeInput{
Endpoint: aws.String(QueueArn),
Protocol: aws.String("sqs"),
TopicArn: createTopicResponse.TopicArn,
})

Subscribe to a public Scaleway function

This code triggers the function each time a message is published to the topic.

You can find the value for [Function URL] in the Scaleway console in the Endpoints tab of your function’s Overview page.

_, _ = awsSns.Subscribe(&sns.SubscribeInput{
Endpoint: aws.String(FunctionUrl),
Protocol: aws.String("lambda"),
TopicArn: createTopicResponse.TopicArn,
})
You can also set up an SQS queue from the same namespace, as a [Dead Letter Queue](/serverless/messaging/concepts/#dead-letter-queue):
```go
_, _ = awsSns.Subscribe(&sns.SubscribeInput{
Attributes: map[string]*string{
"RedrivePolicy": aws.String("{\"deadLetterTargetArn\": \"" + QueueARN + "\"}"),
},
Endpoint: aws.String(FunctionUrl),
Protocol: aws.String("lambda"),
TopicArn: createTopicResponse.TopicArn,
})

Subscribe to an HTTP/S endpoint

_, _ = awsSns.Subscribe(&sns.SubscribeInput{
Endpoint: aws.String(Url),
Protocol: aws.String("http"), // or https
TopicArn: createTopicResponse.TopicArn,
})

The HTTP server should receive an HTTP request with a body in json matching the following format:

{
"Type": "SubscriptionConfirmation",
"Token": "<REDACTED-CONFIRMATION-TOKEN>",
"MessageId": "<REDACTED-MESSAGE-ID>",
"TopicArn": "arn:scw:sns:fr-par:<REDACTED-ID>:MyTopic",
"Message": "You have chosen to subscribe to the topic arn:scw:sns:fr-par:<REDACTED-ID>:MyTopic.\nTo confirm the subscription, visit the SubscribeURL included in this message.",
"Timestamp": "2022-06-29T10:03:34Z",
"SignatureVersion": "1",
"Signature": "<REDACTED-SIGNATURE>",
"SigningCertURL": "https://messaging.s3.fr-par.scw.cloud/fr-par/sns/sns_certificate_[certSerialNumber].crt",
"SubscribeURL": "<THE-CONFIRMATION-LINK>" // Get the confirmation link located here
}

The signing certificate of the message is in the JSON of the SigningCertURL. This certificate is also signed by the trust chain certificate (common name sns.mnq.srr.scw.cloud). For more information about verifying the authenticity of the message, refer to the official AWS documentation.

To confirm the subscription, make a request to the SubscribeURL using your browser or curl.

Delete all subscriptions (Go)

listSubscriptions, _ := awsSns.ListSubscriptionsByTopic(&sns.ListSubscriptionsByTopicInput{
TopicArn: createTopicResponse.TopicArn,
})
for _, sub := range listSubscriptions.Subscriptions {
awsSns.Unsubscribe(&sns.UnsubscribeInput{
SubscriptionArn: sub.SubscriptionArn,
})
}

Python

Connect to SNS (Python)

The following code shows you how to connect to SNS using Boto3’s resource(). You could also use client(), but we favor resource() as it is more pythonesque:

sns = boto3.resource('sns',
endpoint_url=[],
aws_access_key_id=[],
aws_secret_access_key=[],
region_name='fr-par')
Note:

The endpoint_url for Scaleway Messaging and Queuing is https://sqs-sns.mnq.fr-par.scw.cloud. The values for the access and secret keys should be the credentials you generated for your SQS/SNS namespace.

Once connected to the SNS service, you can use any of the SDK’s available functions. However, some functions are not supported by Scaleway Messaging and Queuing, so do check the link to make sure. See the official SDK documentation for more information, or keep reading for some code examples.

Create topic (Python)

# Create a topic. This returns an SNS.Topic instance
topic = sns.create_topic(Name='test') # You can now access identifiers and attributes
print(topic.arn)
print(topic.attributes)

Publish messages to this topic (Python)

Be careful: messages sent to topics with no subscriptions are automatically deleted

for i in range (0,10):
topic.publish(Message="Hello World: "+str(i))

Create subscriptions to this topic (Python)

Subscribe to an SQS queue from the same namespace

subscription = topic.subscribe(
Protocol='sqs',
Endpoint=[Queue ARN],
ReturnSubscriptionArn=True
)

Subscribe to a public Scaleway function

This code triggers the function each time a message is published to the topic.

You can find the value for [Function URL] in the Scaleway console in the Endpoints tab of your function’s Overview page.

subscription_functions = topic.subscribe(
Protocol='lambda',
Endpoint=[Function URL],
ReturnSubscriptionArn=True
)

You can also set up an SQS queue from the same namespace, as a Dead Letter Queue:

subscription_functions = topic.subscribe(
Protocol='lambda',
Endpoint=[Function URL],
ReturnSubscriptionArn=True,
Attributes={
'RedrivePolicy': '{"deadLetterTargetArn": "[Queue ARN]"}'
}
)

Subscribe to an HTTP/S endpoint

subscription = topic.subscribe(
Protocol='http', //or https
Endpoint=url,
ReturnSubscriptionArn=True
)

The HTTP server should receive an HTTP request with a body in json matching the following format:

{
"Type": "SubscriptionConfirmation",
"Token": "<REDACTED-CONFIRMATION-TOKEN>",
"MessageId": "<REDACTED-MESSAGE-ID>",
"TopicArn": "arn:scw:sns:fr-par:<REDACTED-ID>:MyTopic",
"Message": "You have chosen to subscribe to the topic arn:scw:sns:fr-par:<REDACTED-ID>:MyTopic.\nTo confirm the subscription, visit the SubscribeURL included in this message.",
"Timestamp": "2022-06-29T10:03:34Z",
"SignatureVersion": "1",
"Signature": "<REDACTED-SIGNATURE>",
"SigningCertURL": "http://<REDACTED-URL>/SNStest.crt",
"SubscribeURL": "<THE-CONFIRMATION-LINK>" // Get the confirmation link located here
}

To confirm the subscription, make a request to the SubscribeURL using your browser or curl.

Delete all subscriptions (Python)

for subs in topic.subscriptions.all():
subs.delete()

NodeJS

Connect to SNS (NodeJS)

The following code sample shows how to connect to SNS:

import {
CreateTopicCommand,
DeleteTopicCommand,
ListSubscriptionsByTopicCommand,
ListTopicsCommand,
PublishCommand,
SNSClient,
SubscribeCommand,
UnsubscribeCommand,
} from "@aws-sdk/client-sns";
var snsClient = new SNSClient({
credentials : {
accessKeyId : "",
secretAccessKey: ""
},
region: "par",
endpoint: "https://sqs-sns.mnq.fr-par.scw.cloud",
})
Note:

The endpoint_url for Scaleway Messaging and Queuing is https://sqs-sns.mnq.fr-par.scw.cloud. For the access and secret key values, use the credentials you generated for your SQS/SNS namespace.

Once connected to the SNS service, you can use any of the SDK’s available functions. However, some functions are not supported by Scaleway Messaging and Queuing, so do check the link to make sure. See the official SDK documentation for more information, or keep reading for some code examples.

Create topic (NodeJS)

You can find all available parameters for createTopic in the AWS documentation.

var paramsTopic = {
Name: 'MyTopic'
};
const commandCreateTopic = new CreateTopicCommand(paramsTopic);
const restCreateTopic = await snsClient.send(commandCreateTopic);
const topicARN= restCreateTopic.TopicArn;
console.log(topicARN);

Publish messages to this topic (NodeJS)

Be careful: messages sent to topics with no subscriptions are automatically deleted.

This code sample demonstrates how to send a message with MessageAttributes. For more information on MessageAttributes, refer to the official documentation.

var paramsSend = {
Message: 'MyMessage',
Subject: 'MySubject',
TopicArn: topicARN,
};
const commandPublishCommand = new PublishCommand(paramsSend);
const restPublishCommand = await snsClient.send(commandPublishCommand);
console.log(restPublishCommand.MessageId);

Subscribe to a topic (NodeJS)

You can find all available parameters for the subscribe operation in the [AWS documentation] (https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-sns/classes/subscribecommand.html)

Subscribe to an SQS queue from the same namespace

const queueARN = 'YOUR QUEUE ARN';
var paramssubsSQS = {
Protocol: 'sqs', /* required */
TopicArn: topicARN, /* required */
Endpoint: queueARN,
ReturnSubscriptionArn: true
};
const commandSubscribeSQSCommand = new SubscribeCommand(paramssubsSQS);
const restSubscribeCommandSQS = await snsClient.send(commandSubscribeSQSCommand);
console.log(restSubscribeCommandSQS.SubscriptionArn);

Subscribe to a public Scaleway function

This code triggers the function each time a message is published to the topic.

You can find the value for [Function URL] in the Scaleway console in the Endpoints tab of your function’s Overview page.

var params = {
Protocol: 'lambda',
TopicArn: topicARN,
Endpoint: 'YOUR FUNCTION ENDPOINT',
ReturnSubscriptionArn: true
};
const command = new SubscribeCommand(params);
const rest = await snsClient.send(command);
console.log(rest.SubscriptionArn);

You can also set up an SQS queue from the same namespace, as a Dead Letter Queue:

var paramsLambdaSubscription = {
Protocol: 'lambda',
TopicArn: topicARN,
Endpoint: 'YOUR FUNCTION ENDPOINT',
Attributes: {
'RedrivePolicy': '{"deadLetterTargetArn": "SQS Queue Arn"}',
},
ReturnSubscriptionArn: true
};
const commandLambdaSubscription = new SubscribeCommand(paramsLambdaSubscription);
const restLambdaSubscription = await snsClient.send(commandLambdaSubscription);
console.log(restLambdaSubscription.SubscriptionArn);

Subscribe to an HTTP/S endpoint

var paramsHttpsSubscription = {
Protocol: 'https',
TopicArn: topicARN,
Endpoint: 'YOUR SERVER ENDPOINT',
ReturnSubscriptionArn: true
};
const commandHttpsSubscription = new SubscribeCommand(paramsHttpsSubscription);
const restHttpsSubscription = await snsClient.send(commandHttpsSubscription);
console.log(restHttpsSubscription.SubscriptionArn);

The HTTP server receives an HTTP request with a json body matching the following format:

{
"Type": "SubscriptionConfirmation",
"Token": "<REDACTED-CONFIRMATION-TOKEN>",
"MessageId": "<REDACTED-MESSAGE-ID>",
"TopicArn": "arn:scw:sns:fr-par:<REDACTED-ID>:MyTopic",
"Message": "You have chosen to subscribe to the topic arn:scw:sns:fr-par:<REDACTED-ID>:MyTopic.\nTo confirm the subscription, visit the SubscribeURL included in this message.",
"Timestamp": "2022-06-29T10:03:34Z",
"SignatureVersion": "1",
"Signature": "<REDACTED-SIGNATURE>",
"SigningCertURL": "http://<REDACTED-URL>/SNStest.crt",
"SubscribeURL": "<THE-CONFIRMATION-LINK>" // Get the confirmation link located here
}

To confirm the subscription, make a request to the SubscribeURL using your browser or curl.

Delete all subscriptions (NodeJS)

The following code sample deletes all subscriptions to a topic.

var paramsListSubs = {
TopicArn: topicARN,
};
const commandListSubs = new ListSubscriptionsByTopicCommand(paramsListSubs);
const restListSubs = await snsClient.send(commandListSubs);
const subscriptionsList = restListSubs.Subscriptions;
subscriptionsList.forEach(async function (element) {
try {
var params = {
SubscriptionArn: element.SubscriptionArn
};
const command = new UnsubscribeCommand(params)
const rest = await snsClient.send(command)
console.log("Unsubscribing : ",rest.$metadata.httpStatusCode)
} catch (e) {
throw new Error(e.message)
}
});

Delete all topics (NodeJS)

The following code sample deletes all topic in your namespace.

// First List Topics
const commandList = new ListTopicsCommand({});
const restTopicList = await snsClient.send(commandList);
const TopicList = restTopicList.Topics
// For Each Topic in the list, apply the Delete Topic Command
TopicList.forEach(async function (element) {
try {
var params = {
TopicArn: element.TopicArn
};
const command = new DeleteTopicCommand(params)
const rest = await snsClient.send(command)
console.log("Deleting : ",rest.$metadata.httpStatusCode)
} catch (e) {
throw new Error(e.message)
}
});