AWS SQS Integration

Step-by-step guide for sending messages to AWS SQS from a Lambda function, with JavaScript and Python examples.

This guide walks through creating an AWS Lambda function that sends messages to an SQS queue, including SQS setup, IAM policy/role creation, environment variable configuration, and testing.

Step 1 — Create the SQS Queue

  1. Go to the Amazon SQS homepage and click Create Queue.
  2. Choose a queue type and enter a name for the queue.
  3. Scroll to the bottom and click Create queue.
  4. Copy the Queue ARN — you'll need it when creating the IAM policy.

Step 2 — Create the Lambda

  1. Go to the Lambda homepage and click Create function.
  2. Enter a function name. Select Node.js 20.x (JavaScript) or Python 3.12 (Python) as the Runtime.
  3. Click Create function.
  4. In the Code tab, paste the appropriate code below, then click Deploy.

JavaScript (Node.js 20.x)

import { SQSClient, SendMessageCommand } from '@aws-sdk/client-sqs';

const SQS_CLIENT = new SQSClient({ region: 'us-west-2' });
const SQS_URL = process.env.SQS_URL;

const handler = async (event) => {
    try {
        const PARAMS = {
            MessageBody: 'Hello World',
            QueueUrl: SQS_URL
        };

        const COMMAND = new SendMessageCommand(PARAMS);
        const RESULT = await SQS_CLIENT.send(COMMAND);

        return {
            statusCode: 200,
            body: `messageId: ${RESULT.MessageId}`
        };
    } catch (error) {
        console.error('Error:', error);
        return {
            statusCode: 500,
            body: JSON.stringify(`Error sending message to SQS: ${error.message}`)
        };
    }
};

export { handler };

Python 3.12

import boto3
import os

sqs = boto3.client('sqs', region_name='us-west-2')
sqs_url = os.environ['SQS_URL']

def lambda_handler(event, context):
    try:
        params = {
            'MessageBody': 'Hello World',
            'QueueUrl': sqs_url
        }

        response = sqs.send_message(**params)

        return {
            'statusCode': 200,
            'body': f"MessageId: {response['MessageId']}"
        }
    except Exception as e:
        print(f"Error: {e}")
        return {
            'statusCode': 500,
            'body': f"Error sending message to SQS: {str(e)}"
        }

Step 3 — Create the IAM Policy

  1. Go to IAMPoliciesCreate policy.
  2. Select SQS as the service.
  3. Under Actions allowedWrite, select SendMessage.
  4. Under Resources, select Specific and click Add ARNs. Paste the Queue ARN from Step 1.
  5. Click Next, enter a policy name, and click Create policy.

Step 4 — Create the IAM Role

  1. Go to IAMRolesCreate role.
  2. Select AWS service as the trusted entity type and Lambda as the use case. Click Next.
  3. Search for and select the policy you created in Step 3. Click Next.
  4. Enter a role name and click Create role.

Step 5 — Attach the Role to the Lambda

  1. Open your Lambda function → Configuration tab → General configurationEdit.
  2. Set Timeout to 1 minute.
  3. Under Execution role, select Use an existing role and choose the role created in Step 4.
  4. Click Save.

Step 6 — Add the SQS URL Environment Variable

  1. In the Lambda Configuration tab → Environment variablesEdit.
  2. Click Add environment variable.
  3. Set Key to SQS_URL and Value to the URL of your SQS queue.
  4. Click Save.

Step 7 — Test

  1. Go to the Lambda Code tab and click Test.
  2. Enter a name for the test event and click Save, then click Test again.
  3. Under Execution results, verify the response shows statusCode: 200 and a messageId.
  4. Go to your SQS queue → Send and receive messagesPoll for messages to confirm the message was received.