Python
This is a step by step guide on how to receive webhooks from QStash in your Lambda function on AWS.
1. Create a new project
Let’s create a new folder called aws-lambda
and initialize a new project by
creating lambda_function.py
This example uses Makefile, but the scripts can
also be written for Pipenv
.
2. Dependencies
We are using PyJwt
for decoding the JWT token in our code. We will install the
package in the zipping stage.
3. Creating the handler function
In this example we will show how to receive a webhook from QStash and verify the signature.
First, let’s import everything we need:
Now, we create the handler function. In the handler we will prepare all necessary variables that we need for verification. This includes the signature, the signing keys and the url of the lambda function. Then we try to verify the request using the current signing key and if that fails we will try the next one. If the signature could be verified, we can start processing the request.
The verify
function will handle the actual verification of the signature. The
signature itself is actually a JWT and includes claims about
the request. See here.
You can find the complete file here.
That’s it, now we can create the function on AWS and test it.
4. Create a Lambda function on AWS
Create a new Lambda function from scratch by going to the AWS console. (Make sure you select your desired region)
Give it a name and select Python 3.8
as runtime, then create the function.
Afterwards we will add a public URL to this lambda by going to the
Configuration
tab:
Select Auth Type = NONE
because we are handling authentication ourselves.
After creating the url, you should see it on the right side of the overview of your function:
5. Set Environment Variables
Get your current and next signing key from the Upstash Console
On the same Configuration
tab from earlier, we will now set the required
environment variables:
6. Deploy your Lambda function
We need to bundle our code and zip it to deploy it to AWS.
Add the following script to your Makefile
file (or corresponding pipenv
script):
When calling make zip
this will install PyJwt and zip the code.
Afterwards we can click the Upload from
button in the lower right corner and
deploy the code to AWS. Select lambda.zip
as upload file.
7. Publish a message
Open a different terminal and publish a message to QStash. Note the destination url is the URL from step 4.
Next Steps
That’s it, you have successfully created a secure AWS lambda function, that receives and verifies incoming webhooks from qstash.
Learn more about publishing a message to qstash here
Was this page helpful?