Lambda (SAM)
This guide shows you how to work with AWS Lambda using the Serverless Application Model (SAM) and Python. This example demonstrates how to build and run a local API Gateway and Lambda service for direct SDK invocation.
Prerequisites
Section titled “Prerequisites”How to execute
Section titled “How to execute”-
Setup Environment: Run the setup script to install tools and dependencies.
Terminal window scripts/setup.sh -
Start Infrastructure: Launch both SAM local services (API Gateway and Lambda) in separate terminals.
-
API Gateway: to use HTTP requests or cURL:
Terminal window sam local start-api -
Lambda SDK: to use the AWS SDK (boto3) or AWS CLI:
Terminal window sam local start-lambda
-
-
Run the Example:
Terminal window python main.pyTerminal window curl "http://127.0.0.1:3000/get_secret?username=admin"- Install REST Client VS Code extension.
- Open
http/get_secret.http. - Run Click on Send Request above the URL.
- Install AWS CLI.
- Run if you have AWS CLI installed globally:
Terminal window aws lambda invoke --function-name GetSecretFunction --profile sam --payload '{"queryStringParameters": {"username": "admin"}}' output.json - Run if you have AWS CLI installed via mise:
Terminal window mise exec -- aws lambda invoke --function-name GetSecretFunction --profile sam --payload '{"queryStringParameters": {"username": "admin"}}' output.json - Verify the output file
output.json.
How to debug
Section titled “How to debug”Use the preconfigured VS Code debug profiles:
-
Python Script (
main.py):- Ensure the local SAM services are running (
sam local start-apiandsam local start-lambda). - Run the Python: Main debug configuration.
- Ensure the local SAM services are running (
-
Lambda Function:
- Run the SAM: Debug get_secret debug configuration.
How to test
Section titled “How to test”- All tests: Run the automated script:
Terminal window scripts/run_tests.sh - Individually: Use the VS Code Testing tab to run or debug specific test cases.
Validate results
Section titled “Validate results”- Logs: Check the console output in the terminals where
sam localis running to verify invocation details and log messages. - AWS CLI Output: Verify that the generated
output.jsoncontains the expected HTTP response body and status code.
Clean Up
Section titled “Clean Up”- Stop the active SAM local services in your terminals.
- Remove the virtual environment and uninstalled tools:
Terminal window rm -rf .venvmise uninstall -a