Amazon SNS — Developing with AWS SDK to interact Serverless APIs
In this article, we are going to develop Amazon SNS interactions with using AWS SDK.
We are going to do Amazon SNS SDK Examples with using AWS SDK JavaScript v3 and use ES6 standards. By the end of the article, we will invoke SNS API to perform topic related tasks using the latest AWS SDK.
I have just published a new course — AWS Lambda & Serverless — Developer Guide with Hands-on Labs.
Amazon SNS — Developing with AWS SDK
Amazon Simple Notification Service (Amazon SNS) is a web service that coordinates and manages the delivery or sending of messages to subscribing endpoints or clients. In Amazon SNS, there are two types of clients — publishers and subscribers — also referred to as producers and consumers.
Publishers communicate asynchronously with subscribers by producing and sending a message to a topic, which is a logical access point and communication channel. Subscribers (web servers, email addresses, Amazon SQS queues, AWS Lambda functions) consume or receive the message or notification over one of the supported protocols (Amazon SQS, HTTP/S, email, SMS, AWS Lambda) when they are subscribed to the topic.
Amazon SNS Interactions
So when we are interacting with SNS, we will follow topics below :
- Managing Topics like create, delete topics in Amazon SNS
- Publishing Messages in Amazon SNS
- Managing Subscriptions like subscribe and unsubscribe in Amazon SNS
How we can perform these use cases with AWS SDK ?
- With using SNS Client — AWS SDK for JavaScript v3
https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-sns/
Create and Delete Topic on Amazon SNS using AWS SDK
We are going to Create and Delete Topic on Amazon SNS using AWS SDK. In this example, We use a series of Node.js modules to create, list, and delete Amazon SNS topics, and to handle topic attributes. The Node.js modules use the SDK for JavaScript to manage topics using these methods of the SNS client class:
- CreateTopicCommand
- ListTopicsCommand
- DeleteTopicCommand
Create NodeJS Project with SNS SDK Packages
We are going to Create NodeJS Project with SNS SDK Packages to interact with SNS APIs. Open VS Code, create “sns-sdk” folder. This will be our NodeJS project for this section.
Locate folder and run npm command in order to create package.json:
npm init -y
See and edit default package.json is created. The first thing we should do
Add “type”: “module”:
package.json
“keywords”: [],
“author”: “”,
“license”: “ISC”,
“type”: “module” — — — ADDED
}
this provide to use ES6 codes into nodejs projects. for example “import statements”.
Install required SNS sdk packages
Run command on package.json level
npm install @aws-sdk/client-sns
See package installed in package.json file: “@aws-sdk/client-sns”
{
“name”: “section8”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1"
},
“keywords”: [],
“author”: “”,
“license”: “ISC”,
“type”: “module”,
“dependencies”: {
“@aws-sdk/client-sns”: “³.87.0”
}
}
As you can see that node_modules are generated when running npm install command.
Create SNSClient NodeJS Module For Connecting SNS
This section we will interact with SNS. For all these interactions we need to connect SNS, for that purpose we should establish SNSClient object. Instead of creating new client for every SDK request, its best practice to create NodeJS module and use this module for every particular SDK commands.
Create a libs directory, and create a Node.js module with the file name snsClient.js. Copy and paste the code below into it, which creates the SNS client object. Replace REGION with your AWS region.
import { SNSClient } from "@aws-sdk/client-sns";
const REGION = "us-east-2";
const snsClient = new SNSClient({ region: REGION });
export { snsClient };
As you can see that we have created NodeJS module for SNS connections with creating a new instance of SNSClient object. This client object will use every interaction with our SDK examples.
Now we are ready to develop our Topics:
- CreateTopicCommand
- ListTopicsCommand
- DeleteTopicCommand
CreateTopicCommand
Create an object to pass the Name for the new topic to the CreateTopicCommand method of the SNS client class. To call the CreateTopicCommand method, create an asynchronous function invoking an Amazon SNS service object, passing the parameters object. The data returned contains the ARN of the topic.
import { CreateTopicCommand } from “@aws-sdk/client-sns”;
import { snsClient } from “./snsClient.js”;const params = {
Name: “new-topic”
};export const run = async () => {
try {
const data = await snsClient.send(new CreateTopicCommand(params));
console.log(“Success”, data);
} catch (err) {
console.log(“Error”, err);
}
};
run();>
Test
node createtopic.js
Listing Your Topics
Create an empty object to pass to the ListTopicsCommand method of the SNS client class. To call the ListTopicsCommand method, create an asynchronous function invoking an Amazon SNS service object, passing the parameters object. The data returned contains an array of your topic ARNs.
// Import required AWS SDK clients and commands for Node.js
import {ListTopicsCommand } from “@aws-sdk/client-sns”;
import {snsClient } from “./libs/snsClient.js”;const run = async () => {
try {
const data = await snsClient.send(new ListTopicsCommand({}));
console.log(“Success.”, data);
return data; // For unit tests.
} catch (err) {
console.log(“Error”, err.stack);
}
};
run();>
Test
node sns_createtopic.js
Deleting a Topic
To call the DeleteTopicCommand method, create an asynchronous function invoking an Amazon SNS client service object, passing the parameters object.
// Load the AWS SDK for Node.js// Import required AWS SDK clients and commands for Node.js
import {DeleteTopicCommand } from “@aws-sdk/client-sns”;
import {snsClient } from “./libs/snsClient.js”;// Set the parameters
const params = { TopicArn: “TOPIC_ARN” }; //TOPIC_ARNconst run = async () => {
try {
const data = await snsClient.send(new DeleteTopicCommand(params));
console.log(“Success.”, data);
return data; // For unit tests.
} catch (err) {
console.log(“Error”, err.stack);
}
};
run();>
Test
node sns_createtopic.js
Publish Message to Topic on Amazon SNS using AWS SDK
We are going to Publish Message to Topic on Amazon SNS using AWS SDK. We will use PublishCommand when sending request to SNS APIs. But Before we publish message we should create a topic:
- CreateTopicCommand
Create an object to pass the Name for the new topic to the CreateTopicCommand method of the SNS client class. To call the CreateTopicCommand method, create an asynchronous function invoking an Amazon SNS service object, passing the parameters object.
// Import required AWS SDK clients and commands for Node.js
import {CreateTopicCommand } from “@aws-sdk/client-sns”;
import {snsClient } from “./libs/snsClient.js”;// Set the parameters
const params = { Name: “TOPIC_NAME” }; //TOPIC_NAMEconst run = async () => {
try {
const data = await snsClient.send(new CreateTopicCommand(params));
console.log(“Success.”, data);
return data; // For unit tests.
} catch (err) {
console.log(“Error”, err.stack);
}
};
run();>
Test
node sns_createtopic.js
PublishCommand
We will create an object containing the parameters for publishing a message, including the message text and the ARN of the Amazon SNStopic. Lets pass the parameters to the PublishCommand method of the SNS client class. create an asynchronous function invoking an Amazon SNS client service object, passing the parameters object.
// 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();>
Test
node sns_createtopic.js
Subscribe and Unsubscribe from Topic on Amazon SNS using AWS SDK
We are going to Subscribe and Unsubscribe from Topic on Amazon SNS using AWS SDK. We will use Subscribe and Unsubscribe commands when sending request to SNS APIs:
- ListSubscriptionsByTopicCommand
- SubscribeCommand
- ConfirmSubscriptionCommand
- UnsubscribeCommand
I am going to skip other commands but if you would like to continue, you can follow the below course.
Step by Step Design AWS Architectures w/ Course
I have just published a new course — AWS Lambda & Serverless — Developer Guide with Hands-on Labs.
In this course, we will learn almost all the AWS Serverless Services with all aspects. We are going to build serverless applications with using AWS Lambda, Amazon API Gateway, Amazon DynamoDB, Amazon Cognito, Amazon S3, Amazon SNS, Amazon SQS, Amazon EventBridge, AWS Step Functions, DynamoDB and Kinesis Streams. This course will be 100% hands-on, and you will be developing a real-world application with hands-on labs together and step by step.
Source Code
Get the Source Code from Serverless Microservices GitHub — Clone or fork this repository, if you like don’t forget the star. If you find or ask anything you can directly open issue on repository.