You can use AWS SAM for this.
Local Testing and Debugging
Use SAM CLI to step-through and debug your code. It provides a
Lambda-like execution environment locally and helps you catch issues
upfront.
You might need to install Docker first as it would be the execution environment used to run the APIs. Setup the sam project first.
$ python3 -m pip install aws-sam-cli
$ sam init # Just choose the first options e.g. <1 - AWS Quick Start Templates>
Now, you would have a file structure like this:
$ tree
.
└── sam-app
├── events
│ └── event.json
├── hello_world
│ ├── app.py
│ ├── __init__.py
│ └── requirements.txt
├── __init__.py
├── README.md
├── template.yaml
└── tests
├── __init__.py
├── integration
│ ├── __init__.py
│ └── test_api_gateway.py
├── requirements.txt
└── unit
├── __init__.py
└── test_handler.py
6 directories, 13 files
2 files that you would be interested at are:
sam-app/hello_world/app.py
- This is where you would put the codes of your Lambda function.
import json
def lambda_handler(event, context):
"""Sample pure Lambda function"""
return {
"statusCode": 200,
"body": json.dumps({
"message": "hello world",
}),
}
sam-app/template.yaml
- This is where you would configure the API e.g. HTTP Method, URL, the location of the code to run, etc.
...
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.9
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello
Method: get
...
Build the app and then you can run your local API already
$ cd sam-app/
$ sam build
$ sam local start-api
Access your local API
- Note that running this the first time might take some time as this is when the environment for the API is setup e.g. creating the image and running the container. Any subsequent calls should be fast already.
$ curl http://127.0.0.1:3000/hello
{"message": "hello world"}
Complete reference for your guidance: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-getting-started-hello-world.html