

# Introduction to testing with the sam local command
<a name="using-sam-cli-local"></a>

Use the AWS Serverless Application Model Command Line Interface (AWS SAM CLI) `sam local` command to test your serverless applications locally.

For an introduction to the AWS SAM CLI, see [What is the AWS SAM CLI?](what-is-sam-overview.md#what-is-sam-cli).

## Prerequisites
<a name="using-sam-cli-local-prerequisites"></a>

To use `sam local`, install the AWS SAM CLI by completing the following:
+ [AWS SAM prerequisites](prerequisites.md).
+ [Install the AWS SAM CLI](install-sam-cli.md).

Before using `sam local`, we recommend a basic understanding of the following:
+ [Configuring the AWS SAM CLI](using-sam-cli-configure.md).
+ [Create your application in AWS SAM](using-sam-cli-init.md).
+ [Introduction to building with AWS SAM](using-sam-cli-build.md).
+ [Introduction to deploying with AWS SAM](using-sam-cli-deploy.md).

## Using the sam local command
<a name="using-sam-cli-local-command"></a>

Use the `sam local` command with any of its subcommands to perform different types of local testing for your application.

```
$ sam local <subcommand>
```

To learn more about each subcommand, see the following:
+ **[Intro to sam local generate-event](using-sam-cli-local-generate-event.md)** – Generate AWS service events for local testing.
+ **[Intro to sam local invoke](using-sam-cli-local-invoke.md)** – Initiate a one-time invocation of an AWS Lambda function locally.
+ **[Intro to sam local start-api](using-sam-cli-local-start-api.md)** – Run your Lambda functions using a local HTTP server.
+ **[Intro to sam local start-lambda](using-sam-cli-local-start-lambda.md)** – Run your Lambda functions using a local HTTP server for use with the AWS CLI or SDKs.

# Introduction to testing with sam local generate-event
<a name="using-sam-cli-local-generate-event"></a>

Use the AWS Serverless Application Model Command Line Interface (AWS SAM CLI) `sam local generate-event` subcommand to generate event payload samples for supported AWS services. You can then modify and pass these events to local resources for testing.
+ For an introduction to the AWS SAM CLI, see [What is the AWS SAM CLI?](what-is-sam-overview.md#what-is-sam-cli)
+ For a list of `sam local generate-event` command options, see [sam local generate-event](sam-cli-command-reference-sam-local-generate-event.md).

An *event* is a JSON object that gets generated when an AWS service performs an action or task. These events contain specific information, such as the data that was processed or the timestamp of the event. Most AWS services generate events and each service’s events are formatted uniquely for its service.

Events generated by one service are passed to other services as an *event source*. For example, an item placed in an Amazon Simple Storage Service (Amazon S3) bucket can generate an event. This event can then be used as the event source for an AWS Lambda function to process the data further.

Events that you generate with `sam local generate-event` are formatted in the same structure as the actual events created by the AWS service. You can modify the contents of these events and use them to test resources in your application.

## Prerequisites
<a name="using-sam-cli-local-generate-event-prerequisites"></a>

To use `sam local generate-event`, install the AWS SAM CLI by completing the following:
+ [AWS SAM prerequisites](prerequisites.md).
+ [Install the AWS SAM CLI](install-sam-cli.md).

Before using `sam local generate-event`, we recommend a basic understanding of the following:
+ [Configuring the AWS SAM CLI](using-sam-cli-configure.md).
+ [Create your application in AWS SAM](using-sam-cli-init.md).
+ [Introduction to building with AWS SAM](using-sam-cli-build.md).
+ [Introduction to deploying with AWS SAM](using-sam-cli-deploy.md).

## Generate sample events
<a name="using-sam-cli-local-generate-event-generate"></a>

Use the AWS SAM CLI `sam local generate-event` subcommand to generate events for supported AWS services.

**To see a list of supported AWS services**

1. Run the following:

   ```
   $ sam local generate-event
   ```

1. The list of supported AWS services will display. The following is an example:

   ```
   $ sam local generate-event
   ...
   Commands:
     alb
     alexa-skills-kit
     alexa-smart-home
     apigateway
     appsync
     batch
     cloudformation
     ...
   ```

**To generate a local event**

1. Run `sam local generate-event` and provide the supported service name. This will display a list of event types that you can generate. The following is an example:

   ```
   $ sam local generate-event s3
   
   Usage: sam local generate-event s3 [OPTIONS] COMMAND [ARGS]...
   
   Options:
     -h, --help  Show this message and exit.
   
   Commands:
     batch-invocation  Generates an Amazon S3 Batch Operations Invocation Event
     delete            Generates an Amazon S3 Delete Event
     put               Generates an Amazon S3 Put Event
   ```

1. To generate the sample event, run `sam local generate-event`, providing the service and event type.

   ```
   $ sam local generate-event <service> <event>
   ```

   The following is an example:

   ```
   $ sam local generate-event s3 put
   {
     "Records": [
       {
         "eventVersion": "2.0",
         "eventSource": "aws:s3",
         "awsRegion": "us-east-1",
         "eventTime": "1970-01-01T00:00:00.000Z",
         "eventName": "ObjectCreated:Put",
         "userIdentity": {
           "principalId": "EXAMPLE"
         },
         "requestParameters": {
           "sourceIPAddress": "127.0.0.1"
         },
         "responseElements": {
           "x-amz-request-id": "EXAMPLE123456789",
           "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH"
         },
         "s3": {
           "s3SchemaVersion": "1.0",
           "configurationId": "testConfigRule",
           "bucket": {
             "name": "sam-s3-demo-bucket",
             "ownerIdentity": {
               "principalId": "EXAMPLE"
             },
             "arn": "arn:aws:s3:::sam-s3-demo-bucket"
           },
           "object": {
             "key": "test/key",
             "size": 1024,
             "eTag": "0123456789abcdef0123456789abcdef",
             "sequencer": "0A1B2C3D4E5F678901"
           }
         }
       }
     ]
   }
   ```

These sample events contain placeholder values. You can modify these values to reference actual resources in your application or values to help with local testing.

**To modify a sample event**

1. You can modify sample events at the command prompt. To see your options, run the following:

   ```
   $ sam local generate-event <service> <event> --help
   ```

   The following is an example:

   ```
   $ sam local generate-event s3 put --help
   
   Usage: sam local generate-event s3 put [OPTIONS]
   
   Options:
     --region TEXT       Specify the region name you'd like, otherwise the
                         default = us-east-1
     --partition TEXT    Specify the partition name you'd like, otherwise the
                         default = aws
     --bucket TEXT       Specify the bucket name you'd like, otherwise the
                         default = example-bucket
     --key TEXT          Specify the key name you'd like, otherwise the default =
                         test/key
     --debug             Turn on debug logging to print debug message generated
                         by AWS SAM CLI and display timestamps.
     --config-file TEXT  Configuration file containing default parameter values.
                         [default: samconfig.toml]
     --config-env TEXT   Environment name specifying default parameter values in
                         the configuration file.  [default: default]
     -h, --help          Show this message and exit.
   ```

1. Use any of these options at the command prompt to modify your sample event payload. The following is an example:

   ```
   $ sam local generate-event s3 put--bucket sam-s3-demo-bucket
   
   {
     "Records": [
       {
         "eventVersion": "2.0",
         "eventSource": "aws:s3",
         "awsRegion": "us-east-1",
         "eventTime": "1970-01-01T00:00:00.000Z",
         "eventName": "ObjectCreated:Put",
         "userIdentity": {
           "principalId": "EXAMPLE"
         },
         "requestParameters": {
           "sourceIPAddress": "127.0.0.1"
         },
         "responseElements": {
           "x-amz-request-id": "EXAMPLE123456789",
           "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH"
         },
         "s3": {
           "s3SchemaVersion": "1.0",
           "configurationId": "testConfigRule",
           "bucket": {
             "name": "sam-s3-demo-bucket",
             "ownerIdentity": {
               "principalId": "EXAMPLE"
             },
             "arn": "arn:aws:s3:::sam-s3-demo-bucket"
           },
           "object": {
             "key": "test/key",
             "size": 1024,
             "eTag": "0123456789abcdef0123456789abcdef",
             "sequencer": "0A1B2C3D4E5F678901"
           }
         }
       }
     ]
   }
   ```

## Use generated events for local testing
<a name="using-sam-cli-local-generate-event-use"></a>

Save your generated events locally and use other `sam local` subcommands to test.

**To save your generated events locally**
+ Run the following:

  ```
  $ sam local generate-event <service> <event> <event-option> > <filename.json>
  ```

  The following is an example of an event being saved as an `s3.json` file in the `events` folder of our project.

  ```
  sam-app$ sam local generate-event s3 put --bucket amzn-s3-demo-bucket > events/s3.json
  ```

**To use a generated event for local testing**
+ Pass the event with other `sam local` subcommands by using the `--event` option.

  The following is an example of using the `s3.json` event to invoke our Lambda function locally:

  ```
  sam-app$ sam local invoke --event events/s3.json S3JsonLoggerFunction
  
  Invoking src/handlers/s3-json-logger.s3JsonLoggerHandler (nodejs18.x)
  Local image is up-to-date
  Using local image: public.ecr.aws/lambda/nodejs:18-rapid-x86_64.
  
  Mounting /Users/.../sam-app/.aws-sam/build/S3JsonLoggerFunction as /var/task:ro,delegated, inside runtime container
  START RequestId: f4f45b6d-2ec6-4235-bc7b-495ec2ae0128 Version: $LATEST
  END RequestId: f4f45b6d-2ec6-4235-bc7b-495ec2ae0128
  REPORT RequestId: f4f45b6d-2ec6-4235-bc7b-495ec2ae0128  Init Duration: 1.23 ms  Duration: 9371.93 ms      Billed Duration: 9372 ms        Memory Size: 128 MB     Max Memory Used: 128 MB
  ```

## Learn more
<a name="using-sam-cli-local-generate-event-learn"></a>

For a list of all `sam local generate-event` options, see [sam local generate-event](sam-cli-command-reference-sam-local-generate-event.md).

For a demo of using `sam local`, see [AWS SAM for local development. Testing AWS Cloud resources from local development environments](https://www.youtube.com/watch?v=NzPqMrdgD1s&list=PLJo-rJlep0ED198FJnTzhIB5Aut_1vDAd&index=24) in the *Serverless Land Sessions with SAM series on YouTube*.

# Introduction to testing with sam local invoke
<a name="using-sam-cli-local-invoke"></a>

Use the AWS Serverless Application Model Command Line Interface (AWS SAM CLI) `sam local invoke` subcommand to initiate a one-time invocation of an AWS Lambda function locally.
+ For an introduction to the AWS SAM CLI, see [What is the AWS SAM CLI?](what-is-sam-overview.md#what-is-sam-cli)
+ For a list of `sam local invoke` command options, see [sam local invoke](sam-cli-command-reference-sam-local-invoke.md).
+ For an example of using `sam local invoke` during a typical development workflow, see [Step 7: (Optional) Test your application locally](serverless-getting-started-hello-world.md#serverless-getting-started-hello-world-test).

**Note**  
It's not recommended to use SAM CLI's local invoke capabilities in untrusted code. To have complete isolation from your local environment, execute the code in the Lambda service directly.

**Note**  
`sam local invoke` supports durable functions with automatic checkpointing and replay capabilities. When invoking durable functions locally, execution state is automatically managed.

## Prerequisites
<a name="using-sam-cli-local-invoke-prerequisites"></a>

To use `sam local invoke`, install the AWS SAM CLI by completing the following:
+ [AWS SAM prerequisites](prerequisites.md).
+ [Install the AWS SAM CLI](install-sam-cli.md).

Before using `sam local invoke`, we recommend a basic understanding of the following:
+ [Configuring the AWS SAM CLI](using-sam-cli-configure.md).
+ [Create your application in AWS SAM](using-sam-cli-init.md).
+ [Introduction to building with AWS SAM](using-sam-cli-build.md).
+ [Introduction to deploying with AWS SAM](using-sam-cli-deploy.md).

## Invoke a Lambda function locally
<a name="using-sam-cli-local-invoke-use"></a>

When you run `sam local invoke`, the AWS SAM CLI assumes that your current working directory is your project’s root directory. The AWS SAM CLI will first look for a `template.[yaml|yml]` file within a `.aws-sam` subfolder. If not found, the AWS SAM CLI will look for a `template.[yaml|yml]` file within your current working directory.

**To invoke a Lambda function locally**

1. From the root directory of your project, run the following:

   ```
   $ sam local invoke <options>
   ```

1. If your application contains more than one function, provide the function’s logical ID. The following is an example:

   ```
   $ sam local invoke HelloWorldFunction
   ```

1. The AWS SAM CLI builds your function in a local container using Docker. It then invokes your function and outputs your function’s response.

   The following is an example:

   ```
   $ sam local invoke
   Invoking app.lambda_handler (python3.9)
   Local image is out of date and will be updated to the latest runtime. To skip this, pass in the parameter --skip-pull-image
   Building image....................................................................................................................
   Using local image: public.ecr.aws/lambda/python:3.9-rapid-x86_64.
   
   Mounting /Users/.../sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated, inside runtime container
   START RequestId: 64bf7e54-5509-4762-a97c-3d740498d3df Version: $LATEST
   END RequestId: 64bf7e54-5509-4762-a97c-3d740498d3df
   REPORT RequestId: 64bf7e54-5509-4762-a97c-3d740498d3df  Init Duration: 1.09 ms  Duration: 608.42 ms       Billed Duration: 609 ms Memory Size: 128 MB     Max Memory Used: 128 MB
   {"statusCode": 200, "body": "{\"message\": \"hello world\"}"}%
   ```

### Managing logs
<a name="using-sam-cli-local-invoke-logs"></a>

When using `sam local invoke`, the Lambda function runtime output (for example, logs) is output to `stderr`, and the Lambda function result is output to `stdout`.

The following is an example of a basic Lambda function:

```
def handler(event, context):
    print("some log") # this goes to stderr
    return "hello world" # this goes to stdout
```

You can save these standard outputs. The following is an example:

```
$ sam local invoke 1> stdout.log
...

$ cat stdout.log
"hello world"

$ sam local invoke 2> stderr.log
...

$ cat stderr.log
Invoking app.lambda_handler (python3.9)
Local image is up-to-date
Using local image: public.ecr.aws/lambda/python:3.9-rapid-x86_64.
Mounting /Users/.../sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated, inside runtime container
START RequestId: 0b46e646-3bdf-4b58-8beb-242d00912c46 Version: $LATEST
some log
END RequestId: 0b46e646-3bdf-4b58-8beb-242d00912c46
REPORT RequestId: 0b46e646-3bdf-4b58-8beb-242d00912c46  Init Duration: 0.91 ms  Duration: 589.19 ms Billed Duration: 590 ms Memory Size: 128 MB Max Memory Used: 128 MB
```

You can use these standard outputs to further automate your local development processes.

## Options
<a name="using-sam-cli-local-invoke-options"></a>

### Pass custom events to invoke the Lambda function
<a name="using-sam-cli-local-invoke-options-events"></a>

To pass an event to the Lambda function, use the `--event` option. The following is an example:

```
$ sam local invoke --event events/s3.json S3JsonLoggerFunction
```

You can create events with the `sam local generate-event` subcommand. To learn more, see [Introduction to testing with sam local generate-event](using-sam-cli-local-generate-event.md).

### Pass environment variables when invoking your Lambda function
<a name="using-sam-cli-local-invoke-options-env"></a>

If your Lambda function uses environment variables, you can pass them during local testing with the `--env-vars` option. This is a great way to test a Lambda function locally with services in your application that are already deployed in the cloud. The following is an example:

```
$ sam local invoke --env-vars locals.json
```

### Specify a template or function
<a name="using-sam-cli-local-invoke-options-specify"></a>

To specify a template for the AWS SAM CLI to reference, use the `--template` option. The AWS SAM CLI will load just that AWS SAM template and the resources it points to.

To invoke a function of a nested application or stack, provide the application or stack logical ID along with the function logical ID. The following is an example:

```
$ sam local invoke StackLogicalId/FunctionLogicalId
```

### Test a Lambda function from your Terraform project
<a name="using-sam-cli-local-invoke-options-terraform"></a>

Use the `--hook-name` option to locally test Lambda functions from your Terraform projects. To learn more, see [Using the AWS SAM CLI with Terraform for local debugging and testing](using-samcli-terraform.md).

The following is an example:

```
$ sam local invoke --hook-name terraform --beta-features
```

## Best practices
<a name="using-sam-cli-local-invoke-best"></a>

If your application has a `.aws-sam` directory from running `sam build`, be sure to run `sam build` every time you update your function code. Then, run `sam local invoke` to locally test your updated function code.

Local testing is a great solution for quick development and testing before deploying to the cloud. However, local testing doesn’t validate everything, such as permissions between your resources in the cloud. As much as possible, test your applications in the cloud. We recommend [using `sam sync`](using-sam-cli-sync.md) to speed up your cloud testing workflows.

## Examples
<a name="using-sam-cli-local-invoke-examples"></a>

### Generate an Amazon API Gateway sample event and use it to invoke a Lambda function locally
<a name="using-sam-cli-local-invoke-examples-api"></a>

First, we generate an API Gateway HTTP API event payload and save it to our `events` folder.

```
$ sam local generate-event apigateway http-api-proxy > events/apigateway_event.json
```

Next, we modify our Lambda function to return a parameter value from the event.

```
def lambda_handler(event, context):
    print("HelloWorldFunction invoked")
    return {
        "statusCode": 200,
        "body": json.dumps({
            "message": event['queryStringParameters']['parameter2'],
        }),
    }
```

Next, we locally invoke our Lambda function and provide our custom event.

```
$ sam local invoke --event events/apigateway_event.json

Invoking app.lambda_handler (python3.9)
Local image is up-to-date
Using local image: public.ecr.aws/lambda/python:3.9-rapid-x86_64.

Mounting /Users/...sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated, inside runtime container
START RequestId: 59535d0d-3d9e-493d-8c98-6264e8e961b8 Version: $LATEST
some log
END RequestId: 59535d0d-3d9e-493d-8c98-6264e8e961b8
REPORT RequestId: 59535d0d-3d9e-493d-8c98-6264e8e961b8  Init Duration: 1.63 ms  Duration: 564.07 ms       Billed Duration: 565 ms Memory Size: 128 MB     Max Memory Used: 128 MB
{"statusCode": 200, "body": "{\"message\": \"value\"}"}%
```

### Pass environment variables when invoking a Lambda function locally
<a name="using-sam-cli-local-invoke-examples-env"></a>

This application has a Lambda function that uses an environment variable for an Amazon DynamoDB table name. The following is an example of the function defined in the AWS SAM template:

```
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31
...
Resources:
  getAllItemsFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/get-all-items.getAllItemsHandler
      Description: get all items
      Policies:
        - DynamoDBReadPolicy:
            TableName: !Ref SampleTable
      Environment:
        Variables:
          SAMPLE_TABLE: !Ref SampleTable
...
```

We want to locally test our Lambda function while having it interact with our DynamoDB table in the cloud. To do this, we create our environment variables file and save it in our project's root directory as `locals.json`. The value provided here for `SAMPLE_TABLE` references our DynamoDB table in the cloud.

```
{
    "getAllItemsFunction": {
        "SAMPLE_TABLE": "dev-demo-SampleTable-1U991234LD5UM98"
    }
}
```

Next, we run `sam local invoke` and pass in our environment variables with the `--env-vars` option.

```
$ sam local invoke getAllItemsFunction --env-vars locals.json

Mounting /Users/...sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated, inside runtime container
START RequestId: 59535d0d-3d9e-493d-8c98-6264e8e961b8 Version: $LATEST
some log
END RequestId: 59535d0d-3d9e-493d-8c98-6264e8e961b8
REPORT RequestId: 59535d0d-3d9e-493d-8c98-6264e8e961b8  Init Duration: 1.63 ms  Duration: 564.07 ms       Billed Duration: 565 ms Memory Size: 128 MB     Max Memory Used: 128 MB
{"statusCode":200,"body":"{}"}
```

## Learn more
<a name="using-sam-cli-local-invoke-learn"></a>

For a list of all `sam local invoke` options, see [sam local invoke](sam-cli-command-reference-sam-local-invoke.md).

For a demo of using `sam local`, see [AWS SAM for local development. Testing AWS Cloud resources from local development environments](https://www.youtube.com/watch?v=NzPqMrdgD1s&list=PLJo-rJlep0ED198FJnTzhIB5Aut_1vDAd&index=24) in the *Serverless Land Sessions with SAM series on YouTube*.

# Introduction to testing with sam local start-api
<a name="using-sam-cli-local-start-api"></a>

Use the AWS Serverless Application Model Command Line Interface (AWS SAM CLI) `sam local start-api` subcommand to run your AWS Lambda functions locally and test through a local HTTP server host. This type of test is helpful for Lambda functions that are invoked by an Amazon API Gateway endpoint.
+ For an introduction to the AWS SAM CLI, see [What is the AWS SAM CLI?](what-is-sam-overview.md#what-is-sam-cli)
+ For a list of `sam local start-api` command options, see [sam local start-api](sam-cli-command-reference-sam-local-start-api.md).
+ For an example of using `sam local start-api` during a typical development workflow, see [Step 7: (Optional) Test your application locally](serverless-getting-started-hello-world.md#serverless-getting-started-hello-world-test).

**Note**  
`sam local start-api` supports durable functions with automatic checkpointing and replay capabilities. Durable functions work seamlessly with the local API Gateway endpoint.

## Prerequisites
<a name="using-sam-cli-local-start-api-prerequisites"></a>

To use `sam local start-api`, install the AWS SAM CLI by completing the following:
+ [AWS SAM prerequisites](prerequisites.md).
+ [Install the AWS SAM CLI](install-sam-cli.md).

Before using `sam local start-api`, we recommend a basic understanding of the following:
+ [Configuring the AWS SAM CLI](using-sam-cli-configure.md).
+ [Create your application in AWS SAM](using-sam-cli-init.md).
+ [Introduction to building with AWS SAM](using-sam-cli-build.md).
+ [Introduction to deploying with AWS SAM](using-sam-cli-deploy.md).

## Using sam local start-api
<a name="using-sam-cli-local-start-api-use"></a>

When you run `sam local start-api`, the AWS SAM CLI assumes that your current working directory is your project’s root directory. The AWS SAM CLI will first look for a `template.[yaml|yml]` file within a `.aws-sam` subfolder. If not found, the AWS SAM CLI will look for a `template.[yaml|yml]` file within your current working directory.

**To start a local HTTP server**

1. From the root directory of your project, run the following:

   ```
   $ sam local start-api <options>
   ```

1. The AWS SAM CLI builds your Lambda functions in a local Docker container. It then outputs the local address of your HTTP server endpoint. The following is an example:

   ```
   $ sam local start-api
   
   Initializing the lambda functions containers.
   Local image is up-to-date
   Using local image: public.ecr.aws/lambda/python:3.9-rapid-x86_64.
   
   Mounting /Users/.../sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated, inside runtime container
   Containers Initialization is done.
   Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET]
   You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. If you used sam build before running local commands, you will need to re-run sam build for the changes to be picked up. You only need to restart SAM CLI if you update your AWS SAM template
   2023-04-12 14:41:05 WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
    * Running on http://127.0.0.1:3000
   ```

1. You can invoke your Lambda function through the browser or command prompt. The following is an example:

   ```
   sam-app$ curl http://127.0.0.1:3000/hello
   {"message": "Hello world!"}%
   ```

1. When you make changes to your Lambda function code, consider the following to refresh your local HTTP server:
   + If your application doesn’t have a `.aws-sam` directory and your function uses an interpreted language, the AWS SAM CLI will automatically update your function by creating a new container and hosting it.
   + If your application does have a `.aws-sam` directory, you need to run `sam build` to update your function. Then run `sam local start-api` again to host the function.
   + If your function uses a compiled language or if your project requires complex packaging support, run your own build solution to update your function. Then run `sam local start-api` again to host the function.

### Lambda functions that use Lambda authorizers
<a name="using-sam-cli-local-start-api-authorizers"></a>

**Note**  
This feature is new in AWS SAM CLI version 1.80.0. To upgrade, see [Upgrading the AWS SAM CLI](manage-sam-cli-versions.md#manage-sam-cli-versions-upgrade).

For Lambda functions that use Lambda authorizers, the AWS SAM CLI will automatically invoke your Lambda authorizer before invoking your Lambda function endpoint.

The following is an example of starting a local HTTP server for a function that uses a Lambda authorizer:

```
$ sam local start-api
2023-04-17 15:02:13 Attaching import module proxy for analyzing dynamic imports

AWS SAM CLI does not guarantee 100% fidelity between authorizers locally
and authorizers deployed on AWS. Any application critical behavior should
be validated thoroughly before deploying to production.

Testing application behaviour against authorizers deployed on AWS can be done using the sam sync command.

Mounting HelloWorldFunction at http://127.0.0.1:3000/authorized-request [GET]
You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. If you used sam build before running local commands, you will need to re-run sam build for the changes to be picked up. You only need to restart SAM CLI if you update your AWS SAM template
2023-04-17 15:02:13 WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:3000
2023-04-17 15:02:13 Press CTRL+C to quit
```

When you invoke your Lambda function endpoint through the local HTTP server, the AWS SAM CLI first invokes your Lambda authorizer. If authorization is successful, the AWS SAM CLI will invoke your Lambda function endpoint. The following is an example:

```
$ curl http://127.0.0.1:3000/authorized-request --header "header:my_token"
{"message": "from authorizer"}%

Invoking app.authorizer_handler (python3.8)
Local image is up-to-date
Using local image: public.ecr.aws/lambda/python:3.8-rapid-x86_64.

Mounting /Users/.../sam-app/... as /var/task:ro,delegated, inside runtime container
START RequestId: 38d3b472-a2c8-4ea6-9a77-9b386989bef0 Version: $LATEST
END RequestId: 38d3b472-a2c8-4ea6-9a77-9b386989bef0
REPORT RequestId: 38d3b472-a2c8-4ea6-9a77-9b386989bef0    Init Duration: 1.08 ms    Duration: 628.26 msBilled Duration: 629 ms    Memory Size: 128 MB    Max Memory Used: 128 MB
Invoking app.request_handler (python3.8)
Using local image: public.ecr.aws/lambda/python:3.8-rapid-x86_64.

Mounting /Users/.../sam-app/... as /var/task:ro,delegated, inside runtime container
START RequestId: fdc12255-79a3-4365-97e9-9459d06446ff Version: $LATEST
END RequestId: fdc12255-79a3-4365-97e9-9459d06446ff
REPORT RequestId: fdc12255-79a3-4365-97e9-9459d06446ff    Init Duration: 0.95 ms    Duration: 659.13 msBilled Duration: 660 ms    Memory Size: 128 MB    Max Memory Used: 128 MB
No Content-Type given. Defaulting to 'application/json'.
2023-04-17 15:03:03 127.0.0.1 - - [17/Apr/2023 15:03:03] "GET /authorized-request HTTP/1.1" 200 -
```

## Options
<a name="using-sam-cli-local-start-api-options"></a>

### Continuously reuse containers to speed up local function invokes
<a name="using-sam-cli-local-start-api-options-warm"></a>

By default, the AWS SAM CLI creates a new container each time your function is invoked through the local HTTP server. Use the `--warm-containers` option to automatically reuse your container for function invokes. This speeds up the time it takes for the AWS SAM CLI to prepare your Lambda function for local invocation. You can customize this option further by providing the `eager` or `lazy` argument.
+ `eager` – Containers for all functions are loaded at startup and persist between invocations.
+ `lazy` – Containers are only loaded when each function is first invoked. They then persist for additional invocations.

The following is an example:

```
$ sam local start-api --warm-containers eager
```

When using `--warm-containers` and modifying your Lambda function code:
+ If your application has a `.aws-sam` directory, run `sam build` to update your function code in your application’s build artifacts.
+ When a code change is detected, the AWS SAM CLI automatically shuts down the Lambda function container.
+ When you invoke the function again, the AWS SAM CLI automatically creates a new container.

### Specify a container image to use for your Lambda functions
<a name="using-sam-cli-local-start-api-options-specify"></a>

By default, the AWS SAM CLI uses Lambda base images from Amazon Elastic Container Registry (Amazon ECR) to invoke your functions locally. Use the `--invoke-image` option to reference a custom container image. The following is an example:

```
$ sam local start-api --invoke-image public.ecr.aws/sam/emu-python3.8
```

You can specify the function to use with the custom container image. The following is an example:

```
$ sam local start-api --invoke-image Function1=amazon/aws/sam-cli-emulation-image-python3.8
```

### Specify a template to locally test
<a name="using-sam-cli-local-start-api-options-template"></a>

To specify a template for the AWS SAM CLI to reference, use the `--template` option. The AWS SAM CLI will load just that AWS SAM template and the resources it points to. The following is an example:

```
$ sam local start-api --template myTemplate.yaml
```

### Specify the host development environment of your Lambda function
<a name="using-sam-cli-local-start-api-options-dev"></a>

By default, the `sam local start-api` subcommand creates an HTTP server using `localhost` with IP address `127.0.0.1`. You can customize these values if your local development environment is isolated from your local machine.

Use the `--container-host` option to specify a host. The following is an example:

```
$ sam local start-api --container-host host.docker.internal
```

Use the `--container-host-interface` option to specify the IP address of the host network that container ports should bind to. The following is an example:

```
$ sam local start-api --container-host-interface 0.0.0.0
```

## Best practices
<a name="using-sam-cli-local-start-api-best"></a>

If your application has a `.aws-sam` directory from running `sam build`, be sure to run `sam build` every time you update your function code. Then, run `sam local start-api` to locally test your updated function code.

Local testing is a great solution for quick development and testing before deploying to the cloud. However, local testing doesn’t validate everything, such as permissions between your resources in the cloud. As much as possible, test your applications in the cloud. We recommend [using `sam sync`](using-sam-cli-sync.md) to speed up your cloud testing workflows.

## Learn more
<a name="using-sam-cli-local-start-api-learn"></a>

For a list of all `sam local start-api` options, see [sam local start-api](sam-cli-command-reference-sam-local-start-api.md).

# Introduction to testing with sam local start-lambda
<a name="using-sam-cli-local-start-lambda"></a>

Use the AWS SAM CLI subcommand `sam local start-lambda` to invoke your Lambda function through the AWS CLI and SDKs. This command starts a local endpoint that emulates Lambda.
+ For an introduction to the AWS SAM CLI, see [What is the AWS SAM CLI?](what-is-sam-overview.md#what-is-sam-cli)
+ For a list of `sam local start-lambda` command options, see [sam local start-lambda](sam-cli-command-reference-sam-local-start-lambda.md).

**Note**  
`sam local start-lambda` supports durable functions with automatic checkpointing and replay capabilities. Durable functions work seamlessly with the local Lambda endpoint.

## Prerequisites
<a name="using-sam-cli-local-start-api-prerequisites"></a>

To use `sam local start-lambda`, install the AWS SAM CLI by completing the following:
+ [AWS SAM prerequisites](prerequisites.md).
+ [Install the AWS SAM CLI](install-sam-cli.md).

Before using `sam local start-lambda`, we recommend a basic understanding of the following:
+ [Configuring the AWS SAM CLI](using-sam-cli-configure.md).
+ [Create your application in AWS SAM](using-sam-cli-init.md).
+ [Introduction to building with AWS SAM](using-sam-cli-build.md).
+ [Introduction to deploying with AWS SAM](using-sam-cli-deploy.md).

## Using sam local start-lambda
<a name="using-sam-cli-local-start-lambda-use"></a>

When you run `sam local start-lambda`, the AWS SAM CLI assumes that your current working directory is your project’s root directory. The AWS SAM CLI will first look for a `template.[yaml|yml]` file within a `.aws-sam` subfolder. If not found, the AWS SAM CLI will look for a `template.[yaml|yml]` file within your current working directory.

**To use sam local start-lambda**

1. From the root directory of your project, run the following:

   ```
   $ sam local start-lambda <options>
   ```

1. The AWS SAM CLI builds your Lambda functions in a local Docker container. It then outputs the local address to your HTTP server endpoint. The following is an example:

   ```
   $ sam local start-lambda
   Initializing the lambda functions containers.
   Local image is up-to-date
   Using local image: public.ecr.aws/lambda/python:3.9-rapid-x86_64.
   
   Mounting /Users/.../sam-app/hello_world as /var/task:ro,delegated, inside runtime container
   Containers Initialization is done.
   Starting the Local Lambda Service. You can now invoke your Lambda Functions defined in your template through the endpoint.
   2023-04-13 07:25:43 WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
    * Running on http://127.0.0.1:3001
   2023-04-13 07:25:43 Press CTRL+C to quit
   ```

1. Use the AWS CLI or SDKs to invoke your Lambda function locally.

   The following is an example using the AWS CLI:

   ```
   $ aws lambda invoke --function-name "HelloWorldFunction" --endpoint-url "http://127.0.0.1:3001" --no-verify-ssl out.txt
       
   StatusCode: 200
   (END)
   ```

   The following is an example using the AWS SDK for Python:

   ```
   import boto3
   from botocore.config import Config
   from botocore import UNSIGNED
   
   lambda_client = boto3.client('lambda',
                                endpoint_url="http://127.0.0.1:3001",
                                use_ssl=False,
                                verify=False,
                                config=Config(signature_version=UNSIGNED,
                                              read_timeout=1,
                                              retries={'max_attempts': 0}
                                              )
                               )
   lambda_client.invoke(FunctionName="HelloWorldFunction")
   ```

## Options
<a name="using-sam-cli-local-start-lambda-options"></a>

### Specify a template
<a name="using-sam-cli-local-start-lambda-options-template"></a>

To specify a template for the AWS SAM CLI to reference, use the `--template` option. The AWS SAM CLI will load just that AWS SAM template and the resources it points to. The following is an example:

```
$ sam local start-lambda --template myTemplate.yaml
```

For more information on AWS SAM templates, see [AWS SAM template anatomy](sam-specification-template-anatomy.md).

## Best practices
<a name="using-sam-cli-local-start-lambda-best"></a>

If your application has a `.aws-sam` directory from running `sam build`, be sure to run `sam build` every time you update your function code. Then, run `sam local start-lambda` to locally test your updated function code.

Local testing is a great solution for quick development and testing before deploying to the cloud. However, local testing doesn’t validate everything, such as permissions between your resources in the cloud. As much as possible, test your applications in the cloud. We recommend [using `sam sync`](using-sam-cli-sync.md) to speed up your cloud testing workflows.

## Learn more
<a name="using-sam-cli-local-start-lambda-learn"></a>

For a list of all `sam local start-lambda` options, see [sam local start-lambda](sam-cli-command-reference-sam-local-start-lambda.md).