API Proxy for SQS
Integrating API Gateway with SQS (Simple Queue Service)
4 min readSep 23, 2018
If you want to process API Request asynchronously or add a queue in your application architecture, you landed to the right place.
This article shows how to Integrate Amazon API Gateway as a proxy for SQS (Simple Queue Service).
1. Create SQS queue
- Open AWS console in services, navigate to Simple Queue Service.
- Click on “Create New Queue”
- Give queue a name, in our case it is “sqs-lambda-demo” and hit “Create Queue”
- Remember Queue URL (AWS-ACCT-ID/queue-name) and Queue ARN (AWS-ACCT-ID:queue-name)
2. Create IAM Policy
We will create IAM Policy and Role for AWS API Gateway to push Request Message to Queue.
- Select IAM, Navigate to “policies” and click on “Create Policy”.
- Open JSON editor and add the following policy, click on “Review Policy”, name policy as
apig-sqs-send-msg-policy
and hit “Create Policy”.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "sqs:SendMessage",
"Resource": "arn:aws:sqs:ap-southeast-1:123456789:sqs-lambda-demo"
}
]
}
3. Create IAM Role
- Select IAM, Navigate to “Roles” and click on “Create Role”. Now, select “API Gateway” and click “Next:Permissions”.
- Give a name to the role you created. In my case, it’s
apig-sqs-send-msg-role
, notice that only attached policy is “AmazonAPIGatewayPushToCloudWatchLogs”.
- Once role is created, edit the role and attach
apig-sqs-send-msg-policy
.
4. Create an API Structure
- Select API Gateway, click on “Create API”, name api as
SQSProxy
and hit “Create”.
- Click on “Action” and “create resource” and resource as
v1
. - Click on “v1”, and hit “action > create resource” to create
enquque
. - Click on “enqueue” and hit “action > create method” and from dropdown select “POST”.
5. Integrate the API with SQS
- Click on the “POST” method, in “integration type” click on “AWS service”, provide region and AWS service as “SQS”.
- Set Path override to Queue Path created in step 1.
- Set execution role to the role created in step 3. and hit “save”.
6. Modify API Request
- Click on “Integrate Request”
- Set HTTP header with Name as
Content-Type
and Mapped from as'application/x-www-form-urlencoded
. - In “Request body passthrough” select never and click on “add mapping template”, name it as
application/json
and add the following snippetAction=SendMessage&MessageBody=$input.body
. This step will transform your request body to the one accepted by SQS.
7. Test And Deploy
- AWS api gateway provides functionality to test the API.
- In the request body, add the test data.
{
"data" : "test"
}
- If you followed all the steps correctly, you should get 200 status. yey!!!
- Click on the resource “enqueue” and from “actions” select “Deploy Api”.
- Select or create new stage and deploy the Api.
That’s it! Test your API and deploy in production.