How to put request straight into SQS

You dont need any fancy lambda to post into SQS

January 24, 2017 - 2 minute read -

We were recently switching from Recurly to Stripe, so we decided to rewrite the whole billing logic from scratch. We wanted to catch every hook no matter of what, and it`s 2017 so to go serverless was an obvious choice for this task. We were done with the Lambda, but when we were configuring the API Gateway, we realized hey! We maybe don`t even need the lambda. We maybe can put the webhooks straight into SQS.

We put a few hours into trying to find out how to use it, so I`d like to spare you the time and write a tutorial for it.

First create an SQS queue.

You need a Role to put the messages to the SQS queue

NOTE: Your have to choose “Amazon API Gateway” for the type of the role or later you will have to authorize it.

I`d recommend you to create a role with strict rules. Here is an example policy for it.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Resource": [
                <YOUR SQS QUEUE\`S ARN>
            ],
            "Action": [
                "sqs:SendMessage"
            ]
        }
    ]
}

Setting up the API Gateway

Now here I`m going to assume you are already somewhat familiar with creating routes.

So your integration should look like this. API Gateway

NOTE: You can find your ID in your role ARN or in your SQS ARN

NOTE: The execution role should be your newly created role’s ARN

We have a tiny problem. SQS is expecting URL Encoded message so if you send JSON to it you are going to get an error message like Unable to determine service/operation name to be authorized. To solve this problem, we have to transform the message from JSON to URL Encoded. Fortunately, it can be solved within API Gateway.

Making URL Encoded data from JSON

Under HTTP Headers you have to add a new header and set the Name to Content-Type and the Mapped from to 'application/x-www-form-urlencoded' like this:

HTTP Headers

Then you will have to create a Body Mapping Template. Body mapping template

The Content Type should be application/json and the template sould be Action=SendMessage&MessageBody=$util.urlEncode(($input.json('$'))

The Action part says what SQS should do with the message, in this case, add to the queue. MessageBody should be URL Encoded content, $util.urlEncode(($input.json('$')) means we are encoding the JSON input.