AWS CDKv2 Python Lambda with dependencies — the quick read

Patrick Ryan
2 min readMar 4, 2022

Around Nov of 2021, AWS released the experimental constructs into the CDKv2.

You can get these experimental constructs by installing the ‘xxx-alpha’ package. Keep in mind that this is the bleeding edge and the api could change.

Goal: Create a Python Lambda function with dependencies, and front it with an HttpApi.

“Back in my day….” packaging a Python Lambda function with dependencies and multiple python file dependencies was… a bit cumbersome.

The new constructs make this much easier.

Source code can be found on my Github Repo.

I am assuming you have the following already installed:

  • Docker
  • AWS CLI
  • AWS CDK CLI

CDK Setup Info

Skip this if you are familiar with CDK.

mkdir api-lambda-example
cd api-lambda-example
cdk init app --language python
source .venv/bin/activate
pip install -r requirements.txt

if you have never bootstrapped your AWS account to run the cdk you will needed to run:

cdk bootstrap --profile <name of profile to use if not default>

Add CDK Alpha packages

Add the following to the requirements.txt and pip install again. We need these to create the PythonFunction and HttpApi constructs and integrate the two.

aws-cdk.aws-apigatewayv2-alpha
aws-cdk.aws-apigatewayv2-integrations-alpha
aws-cdk.aws-lambda-python-alpha

Create a folder for the Lambda function

I created a folder called lambda1 and in that folder I added:

  • hello_world.py — this is the typical Python Lambda function. This Lambda function has a dependency on ‘requests’ and another Python script in the same folder
  • requirements.txt — this file specifies the packages required for the Lambda function. You can specify other Python package dependency files, but I went the stand by one.
  • utils.py — just a dependent Python script to make sure all of the files where built together.

CDK Stack

Line 19. This is all you need to do to build your Python Lambda function. The CDK will package up all of the files in the ‘entry’ directory and look for the requirements.txt and build a Python 3.9 Lambda function distribution.

Line 27. This is all you need to do to specify the HttpApi and integrate with the Lambda function.

Line 31. This will print the url you need to hit to execute your lambda function.

The rest of code in the repo was generated by the cdk init command.

Deploy/Destroy

Deploy the stack:

cdk deploy --profile <your profile if not default

Hit the url end point and see the Lambda output.

Destroy the stack

cdk destroy --profile <your profile if not default>

The End

I hope that was helpful… now I am off to build something bigger and better.

--

--