Amazon SQS — Developing with AWS SDK to interact Serverless APIs

In this article, we are going to develop Amazon SQS interactions with using AWS SDK.

Amazon SQS — Developing with AWS SDK

We are going to do Amazon SQS SDK Examples with using AWS SDK JavaScript v3 and use ES6 standards. By the end of the article, we will invoke SQS 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 SQS — Developing with AWS SDK

Amazon Simple Queue Service (SQS) is a fast, reliable, scalable, fully managed message queuing service. Amazon SQS lets you decouple the components of a cloud application. Amazon SQS includes standard queues with high throughput and at-least-once processing, and FIFO queues that provide first-in, first-out (FIFO) delivery and exactly-once processing.

Amazon SQS Queues

Amazon SQS Interactions

The JavaScript API for Amazon SQS is exposed through the SQS client class. So when we are interacting with SQS, we will follow topics below :

  • Using queues in Amazon SQS — create, get, list and delete queues
  • Sending messages in Amazon SQS
  • Receive and Delete Messages to Queue on Amazon SQS using AWS SDK
Amazon SQS — Developing with AWS SDK

How we can perform these use cases with AWS SDK ?

Create, List and Delete Queue on Amazon SQS using AWS SDK

We are going to Create, List and Delete Queue on Amazon SQS using AWS SDK. We will use a series of Node.js modules are used to work with queues. The Node.js modules use the SDK for JavaScript to enable queues to call the following methods of the SQS client class:

  • ListQueuesCommand
  • CreateQueueCommand
  • GetQueueUrlCommand
  • DeleteQueueCommand

Create NodeJS Project with SQS SDK Packages

We are going to Create NodeJS Project with SQS SDK Packages to interact with SQS APIs. Open VS Code, create “sqs-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 SQS SDK packages

Run command on package.json level

npm install @aws-sdk/client-sqs

See package installed in package.json file: “@aws-sdk/client-sqs”

{
“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-sqs”: “³.87.0”
}
}

As you can see that node_modules are generated when running npm install command.

Create SQSClient NodeJS Module For Connecting SQS

This section we will interact with SQS. For all these interactions we need to connect SQS, for that purpose we should establish SQSClient 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.

Amazon SQS — Developing with AWS SDK

Create a libs directory, and create a Node.js module with the file name sqsClient.js. Copy and paste the code below into it, which creates the SQS client object. Replace REGION with your AWS region.

import { SQSClient } from “@aws-sdk/client-sqs”;
// Set the AWS Region.
const REGION = “us-east-2”;
// Create SQS service object.
const sqsClient = new SQSClient({ region: REGION });
export { sqsClient };

As you can see that we have created NodeJS module for SQS connections with creating a new instance of SQSClient object. This client object will use every interaction with our SDK examples.

Now we are ready to develop our Topics:

  • CreateQueueCommand

CreateQueueCommand

Create a Node.js module with the file name sqs_createqueue.js. Be sure to configure the SDK as previously shown, including downloading the required clients and packages. We can call the CreateQueueCommand method. The function returns the URL of the created queue.

// Import required AWS SDK clients and commands for Node.js
import { CreateQueueCommand } from “@aws-sdk/client-sqs”;
import { sqsClient } from “./libs/sqsClient.js”;
// Set the parameters
const params = {
QueueName: “SQS_QUEUE_NAME”, //SQS_QUEUE_URL
Attributes: {
DelaySeconds: “60”, // Number of seconds delay.
MessageRetentionPeriod: “86400”, // Number of seconds delay.
},
};
const run = async () => {
try {
const data = await sqsClient.send(new CreateQueueCommand(params));
console.log(“Success”, data);
} catch (err) {
console.log(“Error”, err);
}
};
run();
>
Test
node sqs_createqueue.js

Listing Queues

Create a Node.js module with the file name sqs_listqueues.js. Be sure to configure the SDK as previously shown, including downloading the required clients and packages. We can call the ListQueuesCommand method to retrieve the list of queues. The function returns the URLs of all queues.

// Import required AWS SDK clients and commands for Node.js
import { ListQueuesCommand } from “@aws-sdk/client-sqs”;
import { sqsClient } from “./libs/sqsClient.js”;
const run = async () => {
try {
const data = await sqsClient.send(new ListQueuesCommand({}));
console.log(“Success”, data);
return data; // For unit tests.
} catch (err) {
console.error(err, err.stack);
}
};
run();
>
Test
node sqs_listqueue.js

Deleting a queue

Create a Node.js module with the file name sqs_deletequeue.js. Be sure to configure the SDK as previously shown, including downloading the required clients and packages. We can call the DeleteQueueCommand method.

// Import required AWS SDK clients and commands for Node.js
import { DeleteQueueCommand } from “@aws-sdk/client-sqs”;
import { sqsClient } from “./libs/sqsClient.js”;
// Set the parameters
const params = { QueueUrl: “SQS_QUEUE_URL” }; //SQS_QUEUE_URL e.g., ‘https://sqs.REGION.amazonaws.com/ACCOUNT-ID/QUEUE-NAME'
const run = async () => {
try {
const data = await sqsClient.send(new DeleteQueueCommand(params));
console.log(“Success”, data);
return data; // For unit tests.
} catch (err) {
console.error(err, err.stack);
}
};
run();
>
Test
node sqs_deletequeue.js

Send Messages to Queue on Amazon SQS using AWS SDK

we are going to Send / Receive Messages to Queue on Amazon SQS using AWS SDK. We will learn

  • How to send messages in a queue.
  • How to receive messages in a queue.
  • How to delete messages in a queue.

Sending a message to a queue

Create a Node.js module with the file name sqs_sendmessage.js. Be sure to configure the SDK as previously shown, including downloading the required clients and packages. We can call the SendMessageCommand method. The callback returns the unique ID of the message.

// Import required AWS SDK clients and commands for Node.js
import { SendMessageCommand } from “@aws-sdk/client-sqs”;
import { sqsClient } from “./libs/sqsClient.js”;
// Set the parameters
const params = {
DelaySeconds: 10,
MessageAttributes: {
Title: {
DataType: “String”,
StringValue: “The Whistler”,
},
Author: {
DataType: “String”,
StringValue: “John Grisham”,
},
WeeksOn: {
DataType: “Number”,
StringValue: “6”,
},
},
MessageBody:
“Information about current NY Times fiction bestseller for week of 12/11/2016.”,
// MessageDeduplicationId: “TheWhistler”, // Required for FIFO queues
// MessageGroupId: “Group1”, // Required for FIFO queues
QueueUrl: “SQS_QUEUE_URL” //SQS_QUEUE_URL; e.g., ‘https://sqs.REGION.amazonaws.com/ACCOUNT-ID/QUEUE-NAME’
};
const run = async () => {
try {
const data = await sqsClient.send(new SendMessageCommand(params));
console.log(“Success, message sent. MessageID:”, data.MessageId);
return data; // For unit tests.
} catch (err) {
console.log(“Error”, err);
}
};
run();
>
Test
node sqs_sendmessage.js

Receive and Delete Messages to Queue on Amazon SQS using AWS SDK

We are going to Receive and Delete Messages to Queue on Amazon SQS using AWS SDK. Create a Node.js module with the file name sqs_receivemessage.js. Be sure to configure the SDK as previously shown, including downloading the required clients and packages. We can call the ReceiveMessageCommand method. The callback returns an array of Message objects from which you can retrieve ReceiptHandle for each message that you use to later delete that message.

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.

--

--

Mehmet Ozkaya
AWS Lambda & Serverless — Developer Guide with Hands-on Labs

Software Architect | Udemy Instructor | AWS Community Builder | Cloud-Native and Serverless Event-driven Microservices https://github.com/mehmetozkaya