Bootstrap FreeKB - Amazon Web Services (AWS) - Get Simple Queue Service (SQS) Messages using Python boto3
Amazon Web Services (AWS) - Get Simple Queue Service (SQS) Messages using Python boto3


This assumes you are familar with the basic configurations needed to connect to Amazon Web Services (AWS) using Python boto3. If not, check out my article Python (Scripting) - Getting Started with Amazon Web Services (AWS) boto3.

This also assumes you are familiar with Amazon Web Services (AWS) Simple Queue Service (SQS). If not, check out my article Amazon Web Services (AWS) - Getting Started with Simple Queue Service (SQS).

You will need the URL of the queue you want to consume messages on. This can be done using list_queues or get_queue_url. And then receive_message can be used to get/consumes the messages in a queue. This will not delete the message in the queue. Instead, delete_message must be used to delete the message from the queue.

#!/usr/bin/python3
import boto3
client = boto3.client('sqs')

response = client.get_queue_url(
  QueueName='my-first-queue',
  QueueOwnerAWSAccountId='123456789012'
)

print(f"queue URL = {response['QueueUrl']}")

receive_message_response = client.receive_message(QueueUrl=response['QueueUrl'])

print(receive_message_response)

client.close()

 

Here is a more practical example, with try/except/else error handling.

#!/usr/bin/python3
import boto3
import sys

try:
  client = boto3.client('sqs')
except Exception as exception:
  print(exception)
  sys.exit(1)

try:
  response = client.get_queue_url(
    QueueName='my-first-queue',
    QueueOwnerAWSAccountId='123456789012'
  )
except Exception as exception:
  print(exception)
  sys.exit(1)
else:
  print(f"queue URL = {response['QueueUrl']}")

try:
  receive_message_response = client.receive_message(QueueUrl=response['QueueUrl'])
except Exception as exception:
  print(exception)
  sys.exit(1)
else:
  print(receive_message_response)

try:
  client.close()
except Exception as exception:
  print(exception)

 

Something like this should be returned.

{'Messages': 
  [
    {'MessageId': '5508026b-e650-45d8-8482-8d13623d6a6b', 
    'ReceiptHandle': 'AQEBhKT34C9mo3M/q66DSMCafeqm/D78npzFBI1zkUU/fd+tXl94DXxc9mmG4UnBLOHl82bZZ+6TUaOEJPMBastJLlg0fBjiTP09uxDrVIWVFOSmt+g099Qqpc+aRhxBcbAWL8sq/Y4Jjt9f7ElElZ+dzZzgL6L/Pc8pOLzZctsF7LVIaaCujFaH7NdmeK+rd0Nup55dB88bT2SS3PwSGQ9prQTnkU/rvKUFRHcKOwh2X2kc1f0CA+CotoYf6ahZrLUCw9ywikBc00extJxDbWyJd9ssXWbgIZ/7PiG5kk9Br9i26fo5bIzrkEG93svWLIIxnq6FBkOMf1jR2nSz9a6DuGVAQoXI4lxzjJRLjnI7MiQyGV3i8lPsL3XJxsMC7IKFozORKLFqseOuFo5PRh3JuQ==', 
    'MD5OfBody': '5d41402abc4b2a76b9719d911017c592', 
    'Body': 'hello'}
  ], 
  'ResponseMetadata': {
    'RequestId': '5cd074c1-041b-57b3-ba18-2abd21414cf8', 
    'HTTPStatusCode': 200, 
    'HTTPHeaders': {
      'x-amzn-requestid': '5cd074c1-041b-57b3-ba18-2abd21414cf8', 
      'date': 'Tue, 26 Mar 2024 01:21:30 GMT', 
      'content-type': 'text/xml', 
      'content-length': '856', 
      'connection': 'keep-alive'}, 
    'RetryAttempts': 0
  }
}

 

You probably just want to get the message body. Here is a basic example with try except else finally error handling.

#!/usr/bin/python3
import boto3
client = boto3.client('sqs')

response = client.get_queue_url(
  QueueName='my-first-queue',
  QueueOwnerAWSAccountId='123456789012'
)

receive_message_response = client.receive_message(QueueUrl=response['QueueUrl'])

try:
  receive_message_response['Messages']
except KeyError:
  print("there are no messages in queue {response['QueueUrl']}")
else:
  for message in receive_message_response['Messages']:
    print("message['Body'] = {message['Body']}")

client.close()

 

If there are no messages in the queue, then "there are no messages in queue" should be printed. On the other hand, if there are messages in the queue, something like this should be returned.

message['Body'] = Hello World

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter de395a in the box below so that we can be sure you are a human.