The idea of this tutorial is to quickly and practically demonstrate an example of how to test your lambdas locally
First your machine needs to have Node and Python already configured and then you will need to install serverless globally.
npm i -g serverless
The basic structure of the project will be:
.
├── handler.py
└── serverless.yml
handler.py code
import json
import re
def lambda_handler(event, context):
informedEmail = json.loads(event)['email']
result = _validate(informedEmail)
response = {
'statusCode': 200,
'body': result
}
return response
def _validate(email: str) -> str:
emailRegex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
if(re.search(emailRegex, email)):
return "Valid Email"
return "Invalid Email"
The handler.py is basically a very simple code that receives an email in the body json is valid if it really is in the standard of an email through a simple regex
serverless.yml code
service: email-validator
provider:
name: aws
runtime: python3.8
functions:
main:
handler: handler.lambda_handler
The serverless.yml is the file where you define things like lambda region environment variables and profile used for aws testing.
Important points from our serverless.yml the runtime
line where we defined which python version used in the lambda and handler
line where we reference the lambda entry point.
Now how do we test our code?
In your terminal of choice, run:
serverless invoke local --data '"{\"email\": \"test@example.com\"}"' --function main
Expected response when we provide a valid email
{
"statusCode": 200,
"body": "Valid Email"
}
Congratulations!!
Now you know how to test your lambda locally without any problem
Top comments (0)