Bootstrap FreeKB - Amazon Web Services (AWS) - Put a message on a Simple Queue Service (SQS) Queue using python boto3
Amazon Web Services (AWS) - Put a message on a Simple Queue Service (SQS) Queue 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 put messages on. This can be done using list_queues or get_queue_url. And then send_message can be used to put/publish a message on 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']}")

send_message_response = client.send_message(
  QueueUrl=response['QueueUrl'],
  MessageBody='Hello World'
)

print(send_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:
  send_message_response = client.send_message(
    QueueUrl=response['QueueUrl'],
    MessageBody='Hello World'
  )
except Exception as exception:
  print(exception)
  sys.exit(1)
else:
  print(send_message_response)

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

 

Something like this should be returned.

{
  'MD5OfMessageBody': 'b10a8db164e0754105b7a99be72e3fe5', 
  'MessageId': '681f4a2f-a713-42fe-8be3-7df263e2991c', 
  'ResponseMetadata': {
    'RequestId': '2331a234-909e-501c-a65c-fc48b742307c', 
    'HTTPStatusCode': 200, 
    'HTTPHeaders': {
      'x-amzn-requestid': '2331a234-909e-501c-a65c-fc48b742307c', 
      'date': 'Tue, 26 Mar 2024 01:32:12 GMT', 
      'content-type': 'text/xml', 
      'content-length': '378', 
      'connection': 'keep-alive'}, 
    'RetryAttempts': 0
  }
}

 

More realistically, messages will typically be in a structured format, such as a dictionary.

send_message_response = client.send_message(
  QueueUrl=response['QueueUrl'],
  MessageBody='{"foo": "hello", "bar": "world"}'
)

client.close()

 




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 380a60 in the box below so that we can be sure you are a human.