DBN

AWS CDK - Python Lambda

Word count: 542Reading time: 3 min
2022/06/22

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
2
3
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
nvm install node
nvm use node

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
2
3
mkdir ts_cdk_with_python_lambda
cd ts_cdk_with_python_lambda
cdk init app --language typescript

Install Amazon Lambda Python Library.

1
2
npm i @aws-cdk/aws-lambda-python-alpha
npm install

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
2
3
4
5
6
7
8
9
10
11
12
13
import requests

def handler(event, context):
response = requests.get("https://api.ipify.org?format=json")
print(response.text)
return {
'statusCode': 200,
'headers': {
'Content-Type': 'text/plain'
},
'body': f"You have hit {event['path']}\n"
f"IP of lambda server: {response.json().get('ip', None)}"
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { PythonFunction } from "@aws-cdk/aws-lambda-python-alpha";
import { aws_apigateway as apigw, aws_lambda as lambda } from "aws-cdk-lib";


export class TsCdkWithPythonLambdaStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);

// Python Lambda Function
const myPython = new PythonFunction(this, 'MyPythonHandler', {
entry: './lambda_python', // Folder containing lambda
runtime: lambda.Runtime.PYTHON_3_9, // Python version
index: 'main.py', // Name of Python file
handler: 'handler' // Name of method
});

// API Gateway
new apigw.LambdaRestApi(this, 'MyPythonEndpoint', {
handler: myPython
})
}
}

Full documentation on PythonFunction.

Deploy

Bootstrap your AWS account (if first time running AWS CDK). Then deploy!

1
2
3
cdk bootstrap
cdk diff
cdk deploy

Answer “yes” to prompts. If successful, you should see output with your new API URL.

1
2
Outputs:
TsCdkWithPythonLambdaStack.MyPythonEndpointABC = https://xyz.execute-api.us-west-2.amazonaws.com/prod/

Open the API Gateway URL in a browser and check for text output similar to below:

1
2
You have hit /
IP of lambda server: x.x.x.x

Congratulations on using the new AWS Lambda Python module!

Bonus

Upload to GitHub.

1
2
3
4
git add .
git commit -m "python lambda"
git remote add origin https://github.com/<user>/ts_cdk_with_python_lambda.git
git push -u origin main

GitHub ts_cdk_with_python_lambda repo.

References

CATALOG
  1. 1. Prerequisites
  2. 2. Initialize
  3. 3. Lambda and API Gateway
  4. 4. Deploy
  5. 5. Bonus
  6. 6. References