Test AWS Lambda Locally with SAM CLI
Published on · Updated on
Rewrote the Lambda walkthrough with current SAM invocation, event, environment, and debugger guidance; clarified credential and local-test limits.
sam local invoke runs a Lambda function from an AWS SAM template on your computer, using a Lambda-like runtime container and a test event you provide. It is useful for checking handler logic and debugging a specific input before deploying. It does not reproduce the function's AWS execution role or the services around it; code that calls AWS can still reach real resources with credentials available to the local run.
This walkthrough assumes you already have a SAM project and Docker running. For installation and a first Hello World project, see the AWS SAM local setup guide.
Build and invoke one function
Run commands from the directory containing template.yaml. The function's logical ID is the name shown under Resources in that template. If the project has build artifacts in .aws-sam, rebuild after changing code or dependencies so the invocation uses the updated artifact:
sam build
sam local invoke OrdersFunction --event events/order-created.json
Replace OrdersFunction and the event path with names from your project. If dependencies include native code that must match the Lambda Linux environment, build in a container with sam build --use-container. The AWS guide to local invocation documents function IDs, templates, and event files.
An event file is ordinary JSON passed to the handler as its event argument. It does not cause the named AWS service to send an event. To start a fixture for an S3 notification, create the directory if needed, generate a sample, then edit it to cover the case your handler expects:
mkdir -p events
sam local generate-event s3 put --bucket amzn-s3-demo-bucket > events/s3-put.json
sam local invoke S3EventFunction --event events/s3-put.json
Use the generated payload as a starting point, not proof that an S3 notification is configured. Check that your fixture contains the fields your code reads, including URL-encoded object keys where relevant. AWS documents the event generator and the formats used by Lambda with Amazon S3.
Set local environment values
Declare each variable under the function's Environment.Variables in the SAM template first. The --env-vars file supplies local replacements for declared variables; it does not add a new variable that the template omits. This JSON format applies shared values under Parameters and lets a function-specific entry take precedence:
{
"Parameters": {
"STAGE": "local",
"TABLE_NAME": "orders-sandbox"
},
"OrdersFunction": {
"TABLE_NAME": "orders-test"
}
}
sam local invoke OrdersFunction \
--event events/order-created.json \
--env-vars env.local.json
Here, OrdersFunction receives TABLE_NAME=orders-test; other functions receive orders-sandbox. These are runtime environment overrides. If the template has a CloudFormation Parameters section and you need to change a parameter used to configure resources, use --parameter-overrides instead, for example --parameter-overrides ParameterKey=Stage,ParameterValue=local. Keep local configuration files free of credentials and add sensitive files to .gitignore. See AWS's environment variable file reference.
Debug a local invocation
Start a function with a debugger port, then attach an IDE or debugger configured for that function's runtime:
sam local invoke --debug-port 5858 \
--event events/order-created.json OrdersFunction
The port is for the runtime debugger inside the function container; the debugger protocol and IDE settings depend on the language. AWS also supports -d as the short option and documents runtime-specific setup in its SAM local debugging guide.
Check the result and failure cases
For example, suppose GreetingFunction uses this handler to validate a name and return a greeting:
def handler(event, context):
name = event.get("name")
if not isinstance(name, str) or not name:
raise ValueError("name is required")
return {"greeting": f"Hello, {name}!"}
Save this event as events/greeting.json:
{"name":"Ada"}
Run the function and compare its returned JSON with the expected value:
sam local invoke GreetingFunction --event events/greeting.json
{"greeting":"Hello, Ada!"}
Also try valid JSON events with a missing, empty, or wrong-type name, plus a repeated event when duplicate processing matters. SAM must parse the event file before the handler receives it, so malformed JSON in the file is a CLI input error; for an HTTP function, malformed JSON inside event.body is a separate handler case if your code parses that body. Read both the function response and runtime messages. A command finishing or one sample returning successfully is not an assertion and does not establish that other inputs work; put important cases in unit tests or an integration-test harness that compares actual and expected results. Our Lambda unit testing guide shows event fixtures with explicit assertions.
Know what the local run can reach
A function that only transforms its input can run without AWS credentials. If its code uses an AWS SDK, those calls go to actual AWS services, not local stand-ins. Use an isolated development or sandbox account, point the function at test resources, and use short-lived credentials scoped to the actions and resources needed for the test. Before invoking AWS-dependent code, check the selected account with aws sts get-caller-identity --profile dev and use the intended profile for SAM's AWS credential lookup, for example --profile dev. Do not use production credentials or production data for an exploratory local run.
The local container does not assume or validate the Lambda execution role in the template. A successful call made with your local credentials does not show that the deployed function's role has permission. Local tests also cannot prove deployed networking, event-source delivery and retry behavior, service limits, scaling, or performance in Lambda. AWS summarizes these differences in its Lambda testing guide.
Use local invocation for fast handler feedback, then verify AWS wiring and permissions in a non-production AWS environment when those are part of the change. For a broader local-to-cloud development routine, continue with our SAM CLI local development tips.