Quick walk-though on how to publish a Python lambda that uses libraries not included in native Python container.
Read on to see the new AWS Lambda Python module in action.
The example below uses TypeScript to describe a cloud environment and upload a Python lambda function. Why not use the Python AWS CDK? We certainly could, but I prefer TypeScript as it has more documentation examples online.
Prerequisites
Follow all instructions on cdkworkshop to setup AWS CLI, AWS CDK and NodeJS.
Install NPM with NVM. Blog post here.
1 | curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash |
Install AWS CDK v2. Full documentation here.
1 | npm install aws-cdk-lib |
Setup AWS Account and user. Guide here.
1 | aws configure |
Install Docker. Full documentation here.
1 | brew install docker |
Initialize
Create new directory and initialize with CDK.
1 | mkdir ts_cdk_with_python_lambda |
Install Amazon Lambda Python Library.
1 | npm i @aws-cdk/aws-lambda-python-alpha |
Lambda and API Gateway
Create new file lambda_python/main.py
which will contain our lambda function. Notice how this file uses the requests
library to make a HTTP GET request to an external web service.
1 | import requests |
Create new requirements file lambda_python/requirements.txt
1 | requests==2.28.0 |
Open lib/ts_cdk_with_python_lambda-stack.ts
and add a new Python Function and associated API Gateway.
1 | import { Stack, StackProps } from 'aws-cdk-lib'; |
Full documentation on PythonFunction.
Deploy
Bootstrap your AWS account (if first time running AWS CDK). Then deploy!
1 | cdk bootstrap |
Answer “yes” to prompts. If successful, you should see output with your new API URL.
1 | Outputs: |
Open the API Gateway URL in a browser and check for text output similar to below:
1 | You have hit / |
Congratulations on using the new AWS Lambda Python module!
Bonus
Upload to GitHub.
1 | git add . |
GitHub ts_cdk_with_python_lambda repo.