A Quick Way to Test Python Lambda Functions Locally
I'm working on a more expansive post on Lambda functions and API Gateway, but I wanted to share a find that I think is useful when testing Lambda functions written in Python.
The pip package python-lambda-local will help you emulate calling a Lambda function, without having to leave your local machine.
To install and setup, create a simple py file, add a handler function that takes an event, then call the handler, filename and a sample json payload from file.
Here's a simple example:
Install the package. Might be best to use venv, or you can install globally to call it from anywhere on your machine.
pip install python-lambda-local
def handler(event, context):
msg = "Greetings %s from %s!" % (event["name"], event["city"])
return {
'statusCode': 200,
'isBase64Encoded': False,
'body': {
'msg': msg
},
'headers': {
'Content-Type': 'application/json'
}
}
Create an event file with some json in it event.json
{
"name": "Joe",
"city": "Ohio"
}
Run this command to test.
python-lambda-local -f handler app.py event.json
Check for success or error:
RESULT:
{'statusCode': 200, 'isBase64Encoded': False, 'body': {'msg': 'Greetings Joe from Ohio. !'}, 'headers': {'Content-Type': 'application/json'}}
That's all for today. Short and sweet, but it's all part of a larger post that I didn't have time to finish today.
AJ