How To Send And Recieve Messages In Amazon SQS Using Boto3

boto3 aws sqs
Reading Time: 3 minutes

Hi Folks, In this blog first we will see how to create a Queue in Amazon SQS using boto3 after that we will see How To Send And Recieve Messages In Amazon SQS Using Boto3.So stay till last and you will enjoy learning this new thing.

What is Boto3?

Amazon Web Services (AWS) has become a leader in Cloud Computing. We have different ways to automate any task or to automate AWS Infrastructure Provisioning and one

of the ways is by using python scripting with boto3.Boto3 is the name of the python open-source SDK for AWS. It allows you to directly create, update and delete AWS resources from your python scripts.Boto3 is written on top of botocore which is a low-level interface to the AWS API.

What is AWS SQS?

AWS SQS is a fast ,reliable ,fully managed message queue service .It is a webservice that gives you access to message queues that stores messages waiting to be processed.It is a fully manged message queuing service that enables you to decouple and scale microservices, distrubuted systems ,and severless application.

Getting Started

Assuming that you have a supported version of Python installed, you can first set up your environment with:

$ python3 -m virtualenv myenv
$ source myenv/bin/activate

Then, you can install boto3 from pip with:

$ pip install boto3

Creating a Queue

After installing boto3.Next, set up credentials for your AWS account. In this blog, I will use the python OS module to fetch the environment variables. so first export your aws_access_key_id and aws_secret_access_key in your environment file( e.g: .bashrc).

Now create a .py file In which we will have our python script.

import boto3
import os

sqs_client =boto3.client("sqs", region_name="ap-south-1",
    aws_access_key_id=os.environ.get('AWS_ACCESS_KEY'),
                   aws_secret_access_key=os.environ.get('AWS_SECRET_KEY'))
def create_queue():
    
    response = sqs_client.create_queue(
        QueueName="my-first-q",
        Attributes={
            "DelaySeconds": "0",
            "VisibilityTimeout": "60",  # 60 seconds
        }
    )
    print(response)

if __name__ == "__main__":
     create_queue()
    

You can see that I have used create_queue method to create a Queue. Firstly I have given the name of the queue after that I have defined an attribute that is VisibilityTimeout.Here The visibility timeout is the amount of time that the message is invisible in the SQS Queue after a reader picks up that message.

Now run the code and see the output.

$ python3 demo.py
{'QueueUrl': 'https://ap-south-1.queue.amazonaws.com/066282600937/my-first-queue', 'ResponseMetadata': {'RequestId': '789eac70-98fa-5fb7-9df9-f691e575aa06', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '789eac70-98fa-5fb7-9df9-f691e575aa06', 'date': 'Tue, 26 Apr 2022 04:55:43 GMT', 'content-type': 'text/xml', 'content-length': '333'}, 'RetryAttempts': 0}}

Sending a Message

So we have created an Amazon SQS queue now it’s time to send a message to that queue.

import boto3
import os
sqs_client =boto3.client("sqs", region_name="ap-south-1",
    aws_access_key_id=os.environ.get('AWS_ACCESS_KEY'),
                   aws_secret_access_key=os.environ.get('AWS_SECRET_KEY'))
def sendMessage():
    try:
         queue = sqs_client.get_queue_url(QueueName='my-first-q')
         response = sqs_client.send_message(
         QueueUrl=queue['QueueUrl'],
         DelaySeconds=10,
         MessageAttributes={
        'Title': {
            'DataType': 'String',
            'StringValue': 'Cockpit'
        },
        'Author': {
            'DataType': 'String',
            'StringValue': 'Jubair Ahmad'
        },
        'WeeksOn': {
            'DataType': 'Number',
            'StringValue': '6'
        }
    },
         MessageBody=(
        'Information about connection '
        'date 26/04/22.'
    )
)   
         print(response)
    except Exception as e:
        print("Error in sending message \n{}".format(e))
        return None
if __name__ == "__main__":
    sendMessage()

In the above code firstly I am calling get_queue_url method to get the URL of the queue earlier which we have created. By using this URL we will send the message to the same queue. Now run the above code and see the output.

$python3 demo.py
{'MD5OfMessageBody': 'cc7c36365e9e55e34fb7dbfb567a2354', 'MD5OfMessageAttributes': 'e2f0fb85ddaf44c661ac2efb01fdbe49', 'MessageId': '00ceb27e-4010-4e2d-91e5-ba205fcbb84d', 'ResponseMetadata': {'RequestId': '6a54006d-4cd2-524f-8a04-5a8c82fc613f', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '6a54006d-4cd2-524f-8a04-5a8c82fc613f', 'date': 'Tue, 26 Apr 2022 10:39:42 GMT', 'content-type': 'text/xml', 'content-length': '459'}, 'RetryAttempts': 0}}

Getting Message

Now we will create a python function to get the message from an AWS SQS queue.this function will get the message that we earlier send to the queue.

import boto3
import os
sqs_client =boto3.client("sqs", region_name="ap-south-1",
    aws_access_key_id=os.environ.get('AWS_ACCESS_KEY'),
                   aws_secret_access_key=os.environ.get('AWS_SECRET_KEY'))
def getMessage():
    try:
        queue = sqs_client.get_queue_url(QueueName='my-first-q')
        response = sqs_client.receive_message(
        QueueUrl=queue['QueueUrl'],
        AttributeNames=[
        'SentTimestamp'
     ],
        MaxNumberOfMessages=1,
        MessageAttributeNames=[
        'All'
        ],
        VisibilityTimeout=0,
        WaitTimeSeconds=10
        )

        message = response['Messages'][0]
        print(message)
    except Exception as e:
        print("Error in recieving message \n{}".format(e))
        return None
if __name__ == "__main__":
    getMessage()

$python3 demo.py
{'MessageId': '00ceb27e-4010-4e2d-91e5-ba205fcbb84d', 'ReceiptHandle': 'AQEBqjtSOspcNPaS0Kj0yzccn++p07x0TEYTRd7tzd69z1D+WdDsLXXJHB8Un3905MKxihC0Mn8Ps5W294oe3DEBzcKTrEM76Bn5Do53SiCNpNNaPfpH4PJG8oEU7Pk0LGSl/MMQtCUfG1I2PdtTkSGfX//2uvJGlhwMtIL07Mo0x5GH7T8qsWtiEPvlB/wzThkAOiEB8G++pPr1IaOYUzT5x3tHEUOh1o20RdFQrgl9kTN6CTuRDoIagEINLGHIGzfcG739q6CIF/BoGmqn2NqkiYa90xFPDb/xb3FsSBUmsCuIoAh0Irzv1s6ThWG/REYf/A/A8W47sJWLH/woRUyrqf3uXzZafEfi0A2dzzURtaZzrBQiIeKPlorNYsie4pmqIn5C2Q9+gFy3ypv4Q5Nrtw==', 'MD5OfBody': 'cc7c36365e9e55e34fb7dbfb567a2354', 'Body': 'Information about connection date 21/04/22.', 'Attributes': {'SentTimestamp': '1650969582765'}, 'MD5OfMessageAttributes': 'e2f0fb85ddaf44c661ac2efb01fdbe49', 'MessageAttributes': {'Author': {'StringValue': 'Jubair Ahmad', 'DataType': 'String'}, 'Title': {'StringValue': 'Cockpit', 'DataType': 'String'}, 'WeeksOn': {'StringValue': '6', 'DataType': 'Number'}}}

Now you can verify that the message return by get function is that we pushed using the send function.

If you want to see more blog on boto3 go to below link

https://blog.knoldus.com/introduction-to-boto3-and-its-installation/

Refrences:

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sqs.html

Written by 

Jubair Ahmad is a Software Consultant (DevOps)at Knoldus.Inc.He loves learning new technology and also have interest in playing cricket.