

# Test your serverless application with AWS SAM
<a name="serverless-test-and-debug"></a>

After writing and building your application, you will be ready to test your application to verify that it functions correctly. With the AWS SAM command line interface (CLI), you can locally test your serverless application before uploading it to the AWS Cloud. Testing your application helps you confirm the application’s functionality, reliability, and performance all while identifying issues (bugs) that will need to be addressed.

This section provides guidance on common practices you can follow to test your application. The topics in this section focus mostly on the local testing you can do before deploying in the AWS Cloud. Testing before deploying helps you identify issues proactively, reducing unnecessary costs associated with deployment issues. Each topic in this section describes a test you can perform, tells yoxi include href? u the advantages of using it, and includes examples showing you how to perform the test. After testing your application, you’ll be ready to debug any issues you’ve found.

**Topics**
+ [Introduction to testing with the sam local command](using-sam-cli-local.md)
+ [Locally invoke Lambda functions with AWS SAM](serverless-sam-cli-using-invoke.md)
+ [Locally run API Gateway with AWS SAM](serverless-sam-cli-using-start-api.md)
+ [Introduction to cloud testing with sam remote test-event](using-sam-cli-remote-test-event.md)
+ [Introduction to testing in the cloud with sam remote invoke](using-sam-cli-remote-invoke.md)
+ [Automate local integration tests with AWS SAM](serverless-sam-cli-using-automated-tests.md)
+ [Generate sample event payloads with AWS SAM](serverless-sam-cli-using-generate-event.md)
+ [Testing and debugging durable functions](test-and-debug-durable-functions.md)

# 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).

# Locally invoke Lambda functions with AWS SAM
<a name="serverless-sam-cli-using-invoke"></a>

Locally invoking a Lambda function before testing or deploying in the cloud can have a variety of benefits. It allows you to test the logic of your function faster. Testing locally first reduces the likelihood of identifying issues when testing in the cloud or during deployment, which can help you avoid unnecessary costs. Additionally, local testing makes debugging easier to do.

You can invoke your Lambda function locally by using the [sam local invoke](sam-cli-command-reference-sam-local-invoke.md) command and providing the function's logical ID and an event file. **sam local invoke** also accepts `stdin` as an event. For more information about events, see [Event](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-concepts.html#gettingstarted-concepts-event) in the *AWS Lambda Developer Guide*. For information about event message formats from different AWS services, see [Using AWS Lambda with other services](https://docs.aws.amazon.com/lambda/latest/dg/lambda-services.html) in the *AWS Lambda Developer Guide*.

**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**  
The **sam local invoke** command corresponds to the AWS Command Line Interface (AWS CLI) command [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/invoke.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/invoke.html). You can use either command to invoke a Lambda function.

You must run the **sam local invoke** command in the project directory that contains the function that you want to invoke.

 Examples:

```
# Invoking function with event file
$ sam local invoke "Ratings" -e event.json

# Invoking function with event via stdin
$ echo '{"message": "Hey, are you there?" }' | sam local invoke --event - "Ratings"

# For more options
$ sam local invoke --help
```

## Environment variable file
<a name="serverless-sam-cli-using-invoke-environment-file"></a>

To declare environment variables locally that override values defined in your templates, do the following:

1. Create a JSON or `.env` file that contains the environment variables to override.

1. Use the `--env-vars` argument to override values defined in your templates.

The `--env-vars` option supports two file formats. The file format is automatically detected based on the file content.

### Declaring environment variables with JSON
<a name="serverless-sam-cli-using-invoke-environment-file-declaring"></a>

To declare environment variables that apply globally to all resources, specify a `Parameters` object like the following:

```
{
    "Parameters": {
        "TABLE_NAME": "localtable",
        "BUCKET_NAME": "amzn-s3-demo-bucket",
        "STAGE": "dev"
    }
}
```

To declare different environment variables for each resource, specify objects for each resource like the following:

```
{
    "MyFunction1": {
        "TABLE_NAME": "localtable",
        "BUCKET_NAME": "amzn-s3-demo-bucket",
    },
    "MyFunction2": {
        "TABLE_NAME": "localtable",
        "STAGE": "dev"
    }
}
```

When specifying objects for each resource, you can use the following identifiers, listed in order of highest to lowest precedence:

1. `logical_id`

1. `function_id`

1. `function_name`

1. Full path identifier

You can use both of the preceding methods of declaring environment variables together in a single file. When doing so, environment variables that you provided for specific resources take precedence over global environment variables.

Save your environment variables in a JSON file, such as `env.json`.

### Declaring environment variables with .env files
<a name="serverless-sam-cli-using-invoke-environment-file-dotenv"></a>

You can also use a `.env` file to declare environment variables. Variables declared in a `.env` file apply globally to all functions, equivalent to the `Parameters` object in JSON format.

```
TABLE_NAME=localtable
BUCKET_NAME=amzn-s3-demo-bucket
STAGE=dev
```

The `.env` format supports comments (lines starting with `#`) and quoted values.

**Note**  
The `.env` format only supports global environment variables. To declare function-specific environment variables, use the JSON format.

### Overriding environment variable values
<a name="serverless-sam-cli-using-invoke-environment-file-override"></a>

To override environment variables with those defined in your environment variable file, use the `--env-vars` argument with the **invoke** or **start-api** commands. For example:

```
# Using a JSON file
sam local invoke --env-vars env.json

# Using a .env file
sam local invoke --env-vars .env
```

## Layers
<a name="serverless-sam-cli-using-invoke-layers"></a>

If your application includes layers, for information about how to debug issues with layers on your local host, see [Increase efficiency using Lambda layers with AWS SAM](serverless-sam-cli-layers.md).

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

For a hands-on example of invoking functions locally, see [ Module 2 - Run locally](https://s12d.com/sam-ws-en-local) in *The Complete AWS SAM Workshop*.

# Locally run API Gateway with AWS SAM
<a name="serverless-sam-cli-using-start-api"></a>

Locally running Amazon API Gateway can have a variety of benefits. For example, running API Gateway locally allows you to test API endpoints locally before deployment to the AWS cloud. If you test locally first, you can often reduce testing and development in the cloud, which can help reduce costs. Additionally, running locally makes debugging easier. 

To start a local instance of API Gateway that you can use to test HTTP request/response functionality, use the `sam local start-api` AWS SAM CLI command. This functionality features hot reloading so that you can quickly develop and iterate over your functions.

**Note**  
*Hot reloading* is when only the files that changed are refreshed, and the state of the application remains the same. In contrast, *live reloading* is when the entire application is refreshed, and the state of the application is lost.

For instructions on using the `sam local start-api` command, see [Introduction to testing with sam local start-api](using-sam-cli-local-start-api.md).

By default, AWS SAM uses AWS Lambda proxy integrations and supports both `HttpApi` and `Api` resource types. For more information about proxy integrations for `HttpApi` resource types, see [Working with AWS Lambda proxy integrations for HTTP APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html) in the *API Gateway Developer Guide*. For more information about proxy integrations with `Api` resource types, see [Understand API Gateway Lambda proxy integration](https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-create-api-as-simple-proxy) in the *API Gateway Developer Guide*.

**Example**:

```
$ sam local start-api
```

AWS SAM automatically finds any functions within your AWS SAM template that have `HttpApi` or `Api` event sources defined. Then, it mounts the function at the defined HTTP paths.

In the following `Api` example, the `Ratings` function mounts `ratings.py:handler()` at `/ratings` for `GET` requests:

```
Ratings:
  Type: AWS::Serverless::Function
  Properties:
    Handler: ratings.handler
    Runtime: python3.9
    Events:
      Api:
        Type: Api
        Properties:
          Path: /ratings
          Method: get
```

Here is an example `Api` response:

```
// Example of a Proxy Integration response
exports.handler = (event, context, callback) => {
    callback(null, {
        statusCode: 200,
        headers: { "x-custom-header" : "my custom header value" },
        body: "hello world"
    });
}
```

If you modify your function's code, run the `sam build` command for `sam local start-api` to detect your changes.

## Environment variable file
<a name="serverless-sam-cli-using-start-api-environment-variable"></a>

To declare environment variables locally that override values defined in your templates, do the following:

1. Create a JSON file that contains the environment variables to override.

1. Use the `--env-vars` argument to override values defined in your templates.

### Declaring environment variables
<a name="serverless-sam-cli-using-invoke-environment-file-declaring"></a>

To declare environment variables that apply globally to all resources, specify a `Parameters` object like the following:

```
{
    "Parameters": {
        "TABLE_NAME": "localtable",
        "BUCKET_NAME": "amzn-s3-demo-bucket",
        "STAGE": "dev"
    }
}
```

To declare different environment variables for each resource, specify objects for each resource like the following:

```
{
    "MyFunction1": {
        "TABLE_NAME": "localtable",
        "BUCKET_NAME": "amzn-s3-demo-bucket",
    },
    "MyFunction2": {
        "TABLE_NAME": "localtable",
        "STAGE": "dev"
    }
}
```

When specifying objects for each resource, you can use the following identifiers, listed in order of highest to lowest precedence:

1. `logical_id`

1. `function_id`

1. `function_name`

1. Full path identifier

You can use both of the preceding methods of declaring environment variables together in a single file. When doing so, environment variables that you provided for specific resources take precedence over global environment variables.

Save your environment variables in a JSON file, such as `env.json`.

### Overriding environment variable values
<a name="serverless-sam-cli-using-start-api-environment-file-override"></a>

To override environment variables with those defined in your JSON file, use the `--env-vars` argument with the **invoke** or **start-api** commands. For example:

```
$ sam local start-api --env-vars env.json
```

## Layers
<a name="serverless-sam-cli-using-start-api-layers"></a>

If your application includes layers, for information about how to debug issues with layers on your local host, see [Increase efficiency using Lambda layers with AWS SAM](serverless-sam-cli-layers.md).

# Introduction to cloud testing with sam remote test-event
<a name="using-sam-cli-remote-test-event"></a>

Use the AWS Serverless Application Model Command Line Interface (AWS SAM CLI) `sam remote test-event` command to access and manage shareable test events for your AWS Lambda functions.

To learn more about shareable test events, see [Shareable test events](https://docs.aws.amazon.com/lambda/latest/dg/testing-functions.html#creating-shareable-events) in the *AWS Lambda Developer Guide*.

**Topics**
+ [Set up the AWS SAM CLI to use sam remote test-event](#using-sam-cli-remote-test-event-setup)
+ [Using the sam remote test-event command](#using-sam-cli-remote-test-event-use)
+ [Using shareable test events](#using-sam-cli-remote-test-event-invoke)
+ [Managing shareable test events](#using-sam-cli-remote-test-event-manage)

## Prerequisites
<a name="using-sam-cli-remote-test-event-prerequisites"></a>

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

If you already have the AWS SAM CLI installed, we recommend upgrading to the latest version of the AWS SAM CLI version. To learn more, see [Upgrading the AWS SAM CLI](manage-sam-cli-versions.md#manage-sam-cli-versions-upgrade).

Before using `sam remote test-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).
+ [Introduction to using sam sync to sync to AWS Cloud](using-sam-cli-sync.md).

## Set up the AWS SAM CLI to use sam remote test-event
<a name="using-sam-cli-remote-test-event-setup"></a>

Complete the following set up steps to use the AWS SAM CLI `sam remote test-event` command:

1. **Configure the AWS SAM CLI to use your AWS account** – Shareable test events for Lambda can be accessed and managed by users within the same AWS account. To configure the AWS SAM CLI to use your AWS account, see [Configuring the AWS SAM CLI](using-sam-cli-configure.md).

1. **Configure permissions for shareable test events** – To access and manage shareable test events, you must have the proper permissions. To learn more, see [Shareable test events](https://docs.aws.amazon.com/lambda/latest/dg/testing-functions.html#creating-shareable-events) in the *AWS Lambda Developer Guide*.

## Using the sam remote test-event command
<a name="using-sam-cli-remote-test-event-use"></a>

The AWS SAM CLI `sam remote test-event` command provides the following subcommands that you can use to access and manage your shareable test events:
+ `delete` – Delete a shareable test event from the Amazon EventBridge schema registry.
+ `get` – Get a shareable test event from the EventBridge schema registry.
+ `list` – List the existing shareable test events for a function from the EventBridge schema registry.
+ `put` – Save an event from a local file to the EventBridge schema registry.

To list these subcommands using the AWS SAM CLI, run the following:

```
$ sam remote test-event --help
```

### Deleting shareable test events
<a name="using-sam-cli-remote-test-event-use-delete"></a>

You can delete a shareable test event by using the `delete` subcommand along with the following:
+ Provide the name of the shareable test event to delete.
+ Provide an acceptable ID of the Lambda function associated with the event.
+ If you are providing the Lambda function logical ID, you must also provide the AWS CloudFormation stack name associated with the Lambda function.

The following is an example:

```
$ sam remote test-event delete HelloWorldFunction --stack-name sam-app --name demo-event
```

For a list of options to use with the `delete` subcommand, see [sam remote test-event delete](sam-cli-command-reference-remote-test-event-delete.md). You can also run the following from the AWS SAM CLI:

```
$ sam remote test-event delete --help
```

### Getting shareable test events
<a name="using-sam-cli-remote-test-event-use-get"></a>

You can get a shareable test event from the EventBridge schema registry by using the `get` subcommand along with the following:
+ Provide the name of the shareable test event to get.
+ Provide an acceptable ID of the Lambda function associated with the event.
+ If you are providing the Lambda function logical ID, you must also provide the AWS CloudFormation stack name associated with the Lambda function.

The following is an example that gets a shareable test event named `demo-event` that is associated with the `HelloWorldFunction` Lambda function of the `sam-app` stack. This command will print the event to your console.

```
$ sam remote test-event get HelloWorldFunction --stack-name sam-app --name demo-event
```

To get a shareable test event and save it to your local machine, use the `--output-file` option and provide a file path and name. The following is an example that saves `demo-event` as `demo-event.json` in the current working directory:

```
$ sam remote test-event get HelloWorldFunction --stack-name sam-app --name demo-event --output-file demo-event.json
```

For a list of options to use with the `get` subcommand, see [sam remote test-event get](sam-cli-command-reference-remote-test-event-get.md). You can also run the following from the AWS SAM CLI:

```
$ sam remote test-event get --help
```

### Listing shareable test events
<a name="using-sam-cli-remote-test-event-use-list"></a>

You can list all shareable test events for a particular Lambda function from the schema registry. Use the `list` subcommand along with the following:
+ Provide an acceptable ID of the Lambda function associated with the events.
+ If you are providing the Lambda function logical ID, you must also provide the CloudFormation stack name associated with the Lambda function.

The following is an example that obtains a list of all shareable test events associated with the `HelloWorldFunction` Lambda function of the `sam-app` stack:

```
$ sam remote test-event list HelloWorldFunction --stack-name sam-app
```

For a list of options to use with the `list` subcommand, see [sam remote test-event list](sam-cli-command-reference-remote-test-event-list.md). You can also run the following from the AWS SAM CLI:

```
$ sam remote test-event list --help
```

### Saving shareable test events
<a name="using-sam-cli-remote-test-event-use-put"></a>

You can save shareable test events to the EventBridge schema registry. Use the `put` subcommand along with the following:
+ Provide an acceptable ID of the Lambda function associated with the shareable test event.
+ Provide a name for the shareable test event.
+ Provide the file path and name to the local event to upload.

The following is an example that saves the local `demo-event.json` event as `demo-event` and associates it with the `HelloWorldFunction` Lambda function of the `sam-app` stack:

```
$ sam remote test-event put HelloWorldFunction --stack-name sam-app --name demo-event --file demo-event.json
```

If a shareable test event with the same name exists in the EventBridge schema registry, the AWS SAM CLI will not overwrite it. To overwrite, add the `--force` option to your command.

For a list of options to use with the `put` subcommand, see [sam remote test-event put](sam-cli-command-reference-remote-test-event-put.md). You can also run the following from the AWS SAM CLI:

```
$ sam remote test-event put --help
```

## Using shareable test events
<a name="using-sam-cli-remote-test-event-invoke"></a>

Use shareable test events to test your Lambda functions in the AWS Cloud with the `sam remote invoke` command. To learn more, see [Pass shareable test events to a Lambda function in the cloud](using-sam-cli-remote-invoke.md#using-sam-cli-remote-invoke-shareable).

## Managing shareable test events
<a name="using-sam-cli-remote-test-event-manage"></a>

This topic contains examples on how you can manage and use shareable test events.

### Get a shareable test event, modify it, and use it
<a name="using-sam-cli-remote-test-event-manage-example1"></a>

You can get a shareable test event from the EventBridge schema registry, modify it locally, and use the local test event with your Lambda function in the AWS Cloud. The following is an example:

1. **Retrieve the shareable test event** – Use the `sam remote test-event get` subcommand to retrieve a shareable test event for a specific Lambda function and save it locally:

   ```
   $ sam remote test-event get HelloWorldFunction --stack-name sam-app --name demo-event --output-file demo-event.json
   ```

1. **Modify the shareable test event** – Use a text editor of your choice to modify the shareable test event.

1. **Use the shareable test event** – Use the `sam remote invoke` command and provide the file path and name of the event with `--event-file`:

   ```
   $ sam remote invoke HelloWorldFunction --stack-name sam-app --event-file demo-event.json
   ```

### Get a shareable test event, modify it, upload it, and use it
<a name="using-sam-cli-remote-test-event-manage-example2"></a>

You can get a shareable test event from the EventBridge schema registry, modify it locally, and upload it. Then, you can pass the shareable test event directly to your Lambda function in the AWS Cloud. The following is an example:

1. **Retrieve the shareable test event** – Use the `sam remote test-event get` subcommand to retrieve a shareable test event for a specific Lambda function and save it locally:

   ```
   $ sam remote test-event get HelloWorldFunction --stack-name sam-app --name demo-event --output-file demo-event.json
   ```

1. **Modify the shareable test event** – Use a text editor of your choice to modify the shareable test event.

1. **Upload the shareable test event** – Use the `sam remote test-event put` subcommand to upload and save the shareable test event to the EventBridge schema registry. In this example, we use the `--force` option to overwrite an older version of our shareable test:

   ```
   $ sam remote test-event put HelloWorldFunction --stack-name sam-app --name demo-event --file demo-event.json --force
   ```

1. **Pass the shareable test event to your Lambda function** – Use the `sam remote invoke` command to pass the shareable test event directly to your Lambda function in the AWS Cloud:

   ```
   $ sam remote invoke HelloWorldFunction --stack-name sam-app --test-event-name demo-event
   ```

# Introduction to testing in the cloud with sam remote invoke
<a name="using-sam-cli-remote-invoke"></a>

Use the AWS Serverless Application Model Command Line Interface (AWS SAM CLI) `sam remote invoke` command to interact with supported AWS resources in the AWS Cloud. You can use `sam remote invoke` to invoke the following resources:
+ **Amazon Kinesis Data Streams** – Send data records to Kinesis Data Streams applications.
+ **AWS Lambda** – Invoke and pass events to your Lambda functions.
+ **Amazon Simple Queue Service (Amazon SQS)** – Send messages to Amazon SQS queues.
+ **AWS Step Functions** – Invoke Step Functions state machines to start execution.

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 an example of using `sam remote invoke` during a typical development workflow, see [Step 5: Interact with your function in the AWS Cloud](serverless-getting-started-hello-world.md#serverless-getting-started-hello-world-remote-invoke).

**Topics**
+ [Using the sam remote invoke command](#using-sam-cli-remote-invoke-use)
+ [Using sam remote invoke command options](#using-sam-cli-remote-invoke-options)
+ [Configure your project configuration file](#using-sam-cli-remote-invoke-configure)
+ [Examples](#using-sam-cli-remote-invoke-examples)
+ [Related links](#using-sam-cli-remote-invoke-links)

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

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

We also recommend upgrading to the latest version of the AWS SAM CLI. To learn more, see [Upgrading the AWS SAM CLI](manage-sam-cli-versions.md#manage-sam-cli-versions-upgrade).

Before using `sam remote 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).
+ [Introduction to using sam sync to sync to AWS Cloud](using-sam-cli-sync.md).

## Using the sam remote invoke command
<a name="using-sam-cli-remote-invoke-use"></a>

Before using this command, your resource must be deployed to the AWS Cloud.

Use the following command structure and run from your project's root directory:

```
$ sam remote invoke <arguments> <options>
```

**Note**  
This page will show options being provided at the command prompt. You can also configure options in your project’s configuration file instead of passing them at the command prompt. To learn more, [Configure project settings](using-sam-cli-configure.md#using-sam-cli-configure-project).

For a description of `sam remote invoke` arguments and options, see [sam remote invoke](sam-cli-command-reference-remote-invoke.md).

### Using with Kinesis Data Streams
<a name="using-sam-cli-remote-invoke-use-kinesis"></a>

You can send data records to a Kinesis Data Streams application. The AWS SAM CLI will send your data record and return a shard ID and sequence number. The following is an example:

```
$ sam remote invoke KinesisStream --stack-name kinesis-example --event hello-world
	
	Putting record to Kinesis data stream KinesisStream                                                             
	Auto converting value 'hello-world' into JSON '"hello-world"'. If you don't want auto-conversion, please provide
	a JSON string as event                                                                                          
	{
	  "ShardId": "shardId-000000000000",
	  "SequenceNumber": "49646251411914806775980850790050483811301135051202232322"
	}%
```

**To send a data record**

1. Provide a resource ID value as an argument for your Kinesis Data Streams application. For information on valid resource IDs, see [Resource ID](sam-cli-command-reference-remote-invoke.md#sam-cli-command-reference-remote-invoke-args-resource-id).

1. Provide the data record as an event to send to your Kinesis Data Streams application. You can provide the event at the command line using the `--event` option, or from a file using `--event-file`. If you don’t provide an event, the AWS SAM CLI sends an empty event.

### Using with Lambda functions
<a name="using-sam-cli-remote-invoke-use-lambda"></a>

You can invoke a Lambda function in the cloud and pass an empty event or provide an event at the command line or from a file. The AWS SAM CLI will invoke your Lambda function and return its response. The following is an example:

```
$ sam remote invoke HelloWorldFunction --stack-name sam-app

Invoking Lambda Function HelloWorldFunction                                       
START RequestId: d5ef494b-5f45-4086-86fd-d7322fa1a1f9 Version: $LATEST
END RequestId: d5ef494b-5f45-4086-86fd-d7322fa1a1f9
REPORT RequestId: d5ef494b-5f45-4086-86fd-d7322fa1a1f9  Duration: 6.62 ms       Billed Duration: 7 ms     Memory Size: 128 MB     Max Memory Used: 67 MB  Init Duration: 164.06 ms
{"statusCode":200,"body":"{\"message\":\"hello world\"}"}%
```

**To invoke a Lambda function**

1. Provide a resource ID value as an argument for your Lambda function. For information on valid resource IDs, see [Resource ID](sam-cli-command-reference-remote-invoke.md#sam-cli-command-reference-remote-invoke-args-resource-id).

1. Provide an event to send to your Lambda function. You can provide the event at the command line using the `--event` option, or from a file using `--event-file`. If you don’t provide an event, the AWS SAM CLI sends an empty event.

#### Lambda functions configured with response streaming
<a name="using-sam-cli-remote-invoke-invoke-stream"></a>

The `sam remote invoke` command supports Lambda functions that are configured to stream responses. You can configure a Lambda function to stream responses using the `FunctionUrlConfig` property in your AWS SAM templates. When you use `sam remote invoke`, the AWS SAM CLI will automatically detect your Lambda configuration and invoke with response streaming.

For an example, see [Invoke a Lambda function configured to stream responses](#using-sam-cli-remote-invoke-examples-lambda-stream).

#### Pass shareable test events to a Lambda function in the cloud
<a name="using-sam-cli-remote-invoke-shareable"></a>

Shareable test events are test events that you can share with others in the same AWS account. To learn more, see [Shareable test events](https://docs.aws.amazon.com/lambda/latest/dg/testing-functions.html#creating-shareable-events) in the *AWS Lambda Developer Guide*.

##### Accessing and managing shareable test events
<a name="using-sam-cli-remote-invoke-shareable-access"></a>

You can use the AWS SAM CLI `sam remote test-event` command to access and manage shareable test events. For example, you can use `sam remote test-event` to do the following:
+ Retrieve shareable test events from the Amazon EventBridge schema registry.
+ Modify shareable test events locally and upload them to the EventBridge schema registry.
+ Delete shareable test events from the EventBridge schema registry.

To learn more, see [Introduction to cloud testing with sam remote test-event](using-sam-cli-remote-test-event.md).

##### Pass a shareable test event to a Lambda function in the cloud
<a name="using-sam-cli-remote-invoke-shareable-pass"></a>

To pass a shareable test event from the EventBridge schema registry to your Lambda function in the cloud, use the `--test-event-name` option and provide the name of the shareable test event. The following is an example:

```
$ sam remote invoke HelloWorldFunction --stack-name sam-app --test-event-name demo-event
```

If you save the shareable test event locally, you can use the `--event-file` option and provide the file path and name of the local test event. The following is an example:

```
$ sam remote invoke HelloWorldFunction --stack-name sam-app --event-file demo-event.json
```

### Using with Amazon SQS
<a name="using-sam-cli-remote-invoke-use-sqs"></a>

You can send messages to Amazon SQS queues. The AWS SAM CLI returns the following:
+ Message ID
+ MD5 of message body
+ Response metadata

 The following is an example:

```
$ sam remote invoke MySqsQueue --stack-name sqs-example -event hello

Sending message to SQS queue MySqsQueue                                                                         
{
  "MD5OfMessageBody": "5d41402abc4b2a76b9719d911017c592",
  "MessageId": "05c7af65-9ae8-4014-ae28-809d6d8ec652"
}%
```

**To send a message**

1. Provide a resource ID value as an argument for the Amazon SQS queue. For information on valid resource IDs, see [Resource ID](sam-cli-command-reference-remote-invoke.md#sam-cli-command-reference-remote-invoke-args-resource-id).

1. Provide an event to send to your Amazon SQS queue. You can provide the event at the command line using the `--event` option, or from a file using `--event-file`. If you don’t provide an event, the AWS SAM CLI sends an empty event.

### Using with Step Functions
<a name="using-sam-cli-remote-invoke-use-sf"></a>

You can invoke a Step Functions state machine to start execution. The AWS SAM CLI will wait for the state machine workflow to complete and return an output of the last step in the execution. The following is an example:

```
$ sam remote invoke HelloWorldStateMachine --stack-name state-machine-example --event '{"is_developer": true}'

Invoking Step Function HelloWorldStateMachine                                                                   
"Hello Developer World"%
```

**To invoke a state machine**

1. Provide a resource ID value as an argument for the Step Functions state machine. For information on valid resource IDs, see [Resource ID](sam-cli-command-reference-remote-invoke.md#sam-cli-command-reference-remote-invoke-args-resource-id).

1. Provide an event to send to your state machine. You can provide the event at the command line using the `--event` option, or from a file using `--event-file`. If you don’t provide an event, the AWS SAM CLI sends an empty event.

## Using sam remote invoke command options
<a name="using-sam-cli-remote-invoke-options"></a>

This section covers some of the main options that you can use with the `sam remote invoke` command. For a full list of options, see [sam remote invoke](sam-cli-command-reference-remote-invoke.md).

### Pass an event to your resource
<a name="using-sam-cli-remote-invoke-options-event"></a>

Use the following options to pass events to your resources in the cloud:
+ `--event` – Pass an event at the command line.
+ `--event-file` – Pass an event from a file.

#### Lambda examples
<a name="using-sam-cli-remote-invoke-options-event-lambda-examples"></a>

**Use `--event` to pass an event at the command line as a string value:**

```
$ sam remote invoke HelloWorldFunction --stack-name sam-app --event '{"message": "hello!"}'

Invoking Lambda Function HelloWorldFunction                                                                                                                                                                                                                     
START RequestId: b992292d-1fac-4aa2-922a-c9dc5c6fceab Version: $LATEST
END RequestId: b992292d-1fac-4aa2-922a-c9dc5c6fceab
REPORT RequestId: b992292d-1fac-4aa2-922a-c9dc5c6fceab  Duration: 16.41 ms      Billed Duration: 17 ms  Memory Size: 128 MB     Max Memory Used: 67 MB  Init Duration: 185.96 ms
{"statusCode":200,"body":"{\"message\":\"hello!\"}"}%
```

**Use `--event-file` to pass an event from a file and provide the path to the file:**

```
$ cat event.json
			
{"message": "hello from file"}%    
			
$ sam remote invoke HelloWorldFunction --stack-name sam-app --event-file event.json       

Invoking Lambda Function HelloWorldFunction                                                                                                                                                                                                                     
START RequestId: 3bc71f7d-153a-4b1e-8c9a-901d91b1bec9 Version: $LATEST
END RequestId: 3bc71f7d-153a-4b1e-8c9a-901d91b1bec9
REPORT RequestId: 3bc71f7d-153a-4b1e-8c9a-901d91b1bec9  Duration: 21.15 ms      Billed Duration: 22 ms  Memory Size: 128 MB     Max Memory Used: 67 MB
{"statusCode":200,"body":"{\"message\":\"hello from file\"}"}%
```

**Pass an event using `stdin`:**

```
$ cat event.json
			
{"message": "hello from file"}%    
                                                                       
$ cat event.json | sam remote invoke HelloWorldFunction --stack-name sam-app --event-file -

Reading event from stdin (you can also pass it from file with --event-file)                               
Invoking Lambda Function HelloWorldFunction                                                               
START RequestId: 85ecc902-8ad0-4a2b-a8c8-9bb4f65f5a7a Version: $LATEST
END RequestId: 85ecc902-8ad0-4a2b-a8c8-9bb4f65f5a7a
REPORT RequestId: 85ecc902-8ad0-4a2b-a8c8-9bb4f65f5a7a  Duration: 1.36 ms       Billed Duration: 2 ms   Memory Size: 128 MB       Max Memory Used: 67 MB
{"statusCode":200,"body":"{\"message\":\"hello from file\"}"}%
```

### Configure the AWS SAM CLI response output
<a name="using-sam-cli-remote-invoke-options-output"></a>

When you invoke a supported resource with `sam remote invoke`, the AWS SAM CLI returns a response that contains the following:
+ **Request metadata** – Metadata associated with the request. This includes a request ID and request start time.
+ **Resource response** – The response from your resource after being invoked in the cloud.

You can use the `--output` option to configure the AWS SAM CLI output response. The following option values are available:
+ `json` – Metadata and resource response are returned in a JSON structure. The response contains the full SDK output.
+ `text` – Metadata is returned in text structure. The resource response is returned in the output format of the resource.

The following is an example of a `json` output:

```
$ sam remote invoke --stack-name sam-app --output json

Invoking Lambda Function HelloWorldFunction                                                                                                                                                                                                                     
{
  "ResponseMetadata": {
    "RequestId": "3bdf9a30-776d-4a90-94a6-4cccc0fc7b41",
    "HTTPStatusCode": 200,
    "HTTPHeaders": {
      "date": "Mon, 19 Jun 2023 17:15:46 GMT",
      "content-type": "application/json",
      "content-length": "57",
      "connection": "keep-alive",
      "x-amzn-requestid": "3bdf9a30-776d-4a90-94a6-4cccc0fc7b41",
      "x-amzn-remapped-content-length": "0",
      "x-amz-executed-version": "$LATEST",
      "x-amz-log-result": "U1RBUlQgUmVxdWVzdElkOiAzYmRmOWEzMC03NzZkLTRhOTAtOTRhNi00Y2NjYzBmYzdiNDEgVmVyc2lvbjogJExBVEVTVApFTkQgUmVxdWVzdElkOiAzYmRmOWEzMC03NzZkLTRhOTAtOTRhNi00Y2NjYzBmYzdiNDEKUkVQT1JUIFJlcXVlc3RJZDogM2JkZjlhMzAtNzc2ZC00YTkwLTk0YTYtNGNjY2MwZmM3YjQxCUR1cmF0aW9uOiA4LjIzIG1zCUJpbGxlZCBEdXJhdGlvbjogOSBtcwlNZW1vcnkgU2l6ZTogMTI4IE1CCU1heCBNZW1vcnkgVXNlZDogNjggTUIJCg==",
      "x-amzn-trace-id": "root=1-64908d42-17dab270273fcc6b527dd6b8;sampled=0;lineage=2301f8dc:0"
    },
    "RetryAttempts": 0
  },
  "StatusCode": 200,
  "LogResult": "U1RBUlQgUmVxdWVzdElkOiAzYmRmOWEzMC03NzZkLTRhOTAtOTRhNi00Y2NjYzBmYzdiNDEgVmVyc2lvbjogJExBVEVTVApFTkQgUmVxdWVzdElkOiAzYmRmOWEzMC03NzZkLTRhOTAtOTRhNi00Y2NjYzBmYzdiNDEKUkVQT1JUIFJlcXVlc3RJZDogM2JkZjlhMzAtNzc2ZC00YTkwLTk0YTYtNGNjY2MwZmM3YjQxCUR1cmF0aW9uOiA4LjIzIG1zCUJpbGxlZCBEdXJhdGlvbjogOSBtcwlNZW1vcnkgU2l6ZTogMTI4IE1CCU1heCBNZW1vcnkgVXNlZDogNjggTUIJCg==",
  "ExecutedVersion": "$LATEST",
  "Payload": "{\"statusCode\":200,\"body\":\"{\\\"message\\\":\\\"hello world\\\"}\"}"
}%
```

When you specify a `json` output, the entire response is returned to `stdout`. The following is an example:

```
$ sam remote invoke --stack-name sam-app --output json 1> stdout.log

Invoking Lambda Function HelloWorldFunction           
                                                                                                                                                                                                          
$ cat stdout.log
			
{
  "ResponseMetadata": {
    "RequestId": "d30d280f-8188-4372-bc94-ce0f1603b6bb",
    "HTTPStatusCode": 200,
    "HTTPHeaders": {
      "date": "Mon, 19 Jun 2023 17:35:56 GMT",
      "content-type": "application/json",
      "content-length": "57",
      "connection": "keep-alive",
      "x-amzn-requestid": "d30d280f-8188-4372-bc94-ce0f1603b6bb",
      "x-amzn-remapped-content-length": "0",
      "x-amz-executed-version": "$LATEST",
      "x-amz-log-result": "U1RBUlQgUmVxdWVzdElkOiBkMzBkMjgwZi04MTg4LTQzNzItYmM5NC1jZTBmMTYwM2I2YmIgVmVyc2lvbjogJExBVEVTVApFTkQgUmVxdWVzdElkOiBkMzBkMjgwZi04MTg4LTQzNzItYmM5NC1jZTBmMTYwM2I2YmIKUkVQT1JUIFJlcXVlc3RJZDogZDMwZDI4MGYtODE4OC00MzcyLWJjOTQtY2UwZjE2MDNiNmJiCUR1cmF0aW9uOiA0LjE2IG1zCUJpbGxlZCBEdXJhdGlvbjogNSBtcwlNZW1vcnkgU2l6ZTogMTI4IE1CCU1heCBNZW1vcnkgVXNlZDogNjcgTUIJSW5pdCBEdXJhdGlvbjogMTU4LjM5IG1zCQo=",
      "x-amzn-trace-id": "root=1-649091fc-771473c7778689627a6122b7;sampled=0;lineage=2301f8dc:0"
    },
    "RetryAttempts": 0
  },
  "StatusCode": 200,
  "LogResult": "U1RBUlQgUmVxdWVzdElkOiBkMzBkMjgwZi04MTg4LTQzNzItYmM5NC1jZTBmMTYwM2I2YmIgVmVyc2lvbjogJExBVEVTVApFTkQgUmVxdWVzdElkOiBkMzBkMjgwZi04MTg4LTQzNzItYmM5NC1jZTBmMTYwM2I2YmIKUkVQT1JUIFJlcXVlc3RJZDogZDMwZDI4MGYtODE4OC00MzcyLWJjOTQtY2UwZjE2MDNiNmJiCUR1cmF0aW9uOiA0LjE2IG1zCUJpbGxlZCBEdXJhdGlvbjogNSBtcwlNZW1vcnkgU2l6ZTogMTI4IE1CCU1heCBNZW1vcnkgVXNlZDogNjcgTUIJSW5pdCBEdXJhdGlvbjogMTU4LjM5IG1zCQo=",
  "ExecutedVersion": "$LATEST",
  "Payload": "{\"statusCode\":200,\"body\":\"{\\\"message\\\":\\\"hello world\\\"}\"}"
}%
```

The following is an example of a `text` output:

```
$ sam remote invoke --stack-name sam-app --output text

Invoking Lambda Function HelloWorldFunction                                                                                                                                                                                                                     
START RequestId: 4dbacc43-1ec6-47c2-982b-9dc4620144d6 Version: $LATEST
END RequestId: 4dbacc43-1ec6-47c2-982b-9dc4620144d6
REPORT RequestId: 4dbacc43-1ec6-47c2-982b-9dc4620144d6  Duration: 9.13 ms       Billed Duration: 10 ms  Memory Size: 128 MB     Max Memory Used: 67 MB  Init Duration: 165.50 ms
{"statusCode":200,"body":"{\"message\":\"hello world\"}"}%
```

When you specify a `text` output, the Lambda function runtime output (for example, logs) is returned to `stderr`. The Lambda function payload is returned to `stdout`. The following is an example:

```
$ sam remote invoke --stack-name sam-app --output text 2> stderr.log

{"statusCode":200,"body":"{\"message\":\"hello world\"}"}% 
                                                                                                                                                                                                     
$ cat stderr.log

Invoking Lambda Function HelloWorldFunction
START RequestId: 82273c3b-aa3a-4d16-8f1c-1d2ad3ace891 Version: $LATEST
END RequestId: 82273c3b-aa3a-4d16-8f1c-1d2ad3ace891
REPORT RequestId: 82273c3b-aa3a-4d16-8f1c-1d2ad3ace891  Duration: 40.62 ms      Billed Duration: 41 ms  Memory Size: 128 MB     Max Memory Used: 68 MB

$ sam remote invoke --stack-name sam-app --output text 1> stdout.log
 
Invoking Lambda Function HelloWorldFunction                                                                                                                                                                                                                     
START RequestId: 74acaa9f-5b80-4a5c-b3b8-ffaccb84cbbd Version: $LATEST
END RequestId: 74acaa9f-5b80-4a5c-b3b8-ffaccb84cbbd
REPORT RequestId: 74acaa9f-5b80-4a5c-b3b8-ffaccb84cbbd  Duration: 2.31 ms       Billed Duration: 3 ms   Memory Size: 128 MB     Max Memory Used: 67 MB

$ cat stdout.log

{"statusCode":200,"body":"{\"message\":\"hello world\"}"}%
```

### Customize Boto3 parameters
<a name="using-sam-cli-remote-invoke-options-boto3"></a>

For `sam remote invoke`, the AWS SAM CLI utilizes the AWS SDK for Python (Boto3) to interact with your resources in the cloud. You can use the `--parameter` option to customize Boto3 parameters. For a list of supported parameters that you can customize, see `--parameter`.

#### Examples
<a name="using-sam-cli-remote-invoke-options-boto3-examples"></a>

**Invoke a Lambda function to validate parameter values and verify permissions:**

```
$ sam remote invoke HelloWorldFunction --stack-name sam-app --parameter InvocationType="DryRun"
```

**Use the `--parameter` option multiple times in a single command to provide multiple parameters:**

```
$ sam remote invoke HelloWorldFunction --stack-name sam-app --parameter InvocationType="Event" --parameter LogType="None"
```

### Other options
<a name="using-sam-cli-remote-invoke-options-other"></a>

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

## Configure your project configuration file
<a name="using-sam-cli-remote-invoke-configure"></a>

To configure `sam remote invoke` in your configuration file, use `remote_invoke` in your table. The following is an example of a `samconfig.toml` file that configures default values for the `sam remote invoke` command.

```
...
version =0.1

[default]
...
[default.remote_invoke.parameters]
stack_name = "cloud-app"
event = '{"message": "Hello!"}'
```

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

For a basic example of using `sam remote invoke`, see [Testing AWS Lambda functions with AWS SAM remote](https://aws.amazon.com/blogs/compute/testing-aws-lambda-functions-with-aws-sam-remote-invoke/) in the *AWS Compute Blog*.

### Kinesis Data Streams examples
<a name="using-sam-cli-remote-invoke-examples-kinesis"></a>

#### Basic examples
<a name="using-sam-cli-remote-invoke-examples-kinesis-basic"></a>

**Send a data record to a Kinesis Data Streams application from a file. The Kinesis Data Streams application is identified by providing an ARN for the resource ID:**

```
$ sam remote invoke arn:aws:kinesis:us-west-2:01234567890:stream/kinesis-example-KinesisStream-BgnLcAey4xUQ --event-file event.json
```

**Send an event provided at the command line to a Kinesis Data Streams application:**

```
$ sam remote invoke KinesisStream --stack-name kinesis-example --event hello-world

Putting record to Kinesis data stream KinesisStream                                                             
Auto converting value 'hello-world' into JSON '"hello-world"'. If you don't want auto-conversion, please provide
a JSON string as event                                                                                          
{
  "ShardId": "shardId-000000000000",
  "SequenceNumber": "49646251411914806775980903986194508740483329854174920706"
}%
```

**Obtain the physical ID of the Kinesis Data Streams application. Then, provide an event at the command line:**

```
$ sam list resources --stack-name kinesis-example --output json

[
  {
    "LogicalResourceId": "KinesisStream",
    "PhysicalResourceId": "kinesis-example-KinesisStream-ZgnLcQey4xUQ"
  }
]

$ sam remote invoke kinesis-example-KinesisStream-ZgnLcQey4xUQ --event hello

Putting record to Kinesis data stream KinesisStream                                                             
Auto converting value 'hello' into JSON '"hello"'. If you don't want auto-conversion, please provide a JSON     
string as event                                                                                                 
{
  "ShardId": "shardId-000000000000",
  "SequenceNumber": "49646251411914806775980904340716841045751814812900261890"
}%
```

**Provide a JSON string at the command line as an event:**

```
$ sam remote invoke KinesisStream --stack-name kinesis-example --event '{"method": "GET", "body": ""}'                      

Putting record to Kinesis data stream KinesisStream                                                             
{
  "ShardId": "shardId-000000000000",
  "SequenceNumber": "49646251411914806775980904492868617924990209230536441858"
}%
```

**Send an empty event to the Kinesis Data Streams application:**

```
$ sam remote invoke KinesisStream --stack-name kinesis-example

Putting record to Kinesis data stream KinesisStream                                                             
{
  "ShardId": "shardId-000000000000",
  "SequenceNumber": "49646251411914806775980904866469008589597168190416224258"
}%
```

**Return the AWS SAM CLI response in JSON format:**

```
$ sam remote invoke KinesisStream --stack-name kinesis-example --event '{"hello": "world"}' --output json

Putting record to Kinesis data stream KinesisStream                                                             
{
  "ShardId": "shardId-000000000000",
  "SequenceNumber": "49646251411914806775980905078409420803696667195489648642",
  "ResponseMetadata": {
    "RequestId": "ebbbd307-3e9f-4431-b67c-f0715e9e353e",
    "HTTPStatusCode": 200,
    "HTTPHeaders": {
      "x-amzn-requestid": "ebbbd307-3e9f-4431-b67c-f0715e9e353e",
      "x-amz-id-2": "Q3yBcgTwtPaQTV26IKclbECmZikUYOzKY+CzcxA84ZHgCkc5T2N/ITWg6RPOQcWw8Gn0tNPcEJBEHyVVqboJAPgCritqsvCu",
      "date": "Thu, 09 Nov 2023 18:13:10 GMT",
      "content-type": "application/x-amz-json-1.1",
      "content-length": "110"
    },
    "RetryAttempts": 0
  }
}%
```

**Return the JSON output to stdout:**

```
$ sam remote invoke KinesisStream --stack-name kinesis-example --event '{"hello": "world"}' --output json 1> stdout.log

Putting record to Kinesis data stream KinesisStream                                                             

$ cat stdout.log
{
  "ShardId": "shardId-000000000000",
  "SequenceNumber": "49646251411914806775980906397777867595039988349006774274",
  "ResponseMetadata": {
    "RequestId": "f4290006-d84b-b1cd-a9ee-28306eeb2939",
    "HTTPStatusCode": 200,
    "HTTPHeaders": {
      "x-amzn-requestid": "f4290006-d84b-b1cd-a9ee-28306eeb2939",
      "x-amz-id-2": "npCqz+IBKpoL4sQ1ClbUmxuJlbeA24Fx1UgpIrS6mm2NoIeV2qdZSN5AhNurdssykXajBrXaC9anMhj2eG/h7Hnbf+bPuotU",
      "date": "Thu, 09 Nov 2023 18:33:26 GMT",
      "content-type": "application/x-amz-json-1.1",
      "content-length": "110"
    },
    "RetryAttempts": 0
  }
}%
```

### Lambda examples
<a name="using-sam-cli-remote-invoke-examples-lambda"></a>

#### Basic examples
<a name="using-sam-cli-remote-invoke-examples-lambda-basic"></a>

**Invoke a Lambda function by providing the ARN as a resource ID:**

```
$ sam remote invoke arn:aws:lambda:us-west-2:012345678910:function:sam-app-HelloWorldFunction-ohRFEn2RuAvp
```

**Invoke a Lambda function by providing the logical ID as a resource ID:**

You must also provide the CloudFormation stack name using the `--stack-name` option. The following is an example:

```
$ sam remote invoke HelloWorldFunction --stack-name sam-app
```

If your application contains a single Lambda function, you don’t have to specify it’s logical ID. You can provide the `--stack-name` option only. The following is an example:

```
$ sam remote invoke --stack-name sam-app
```

**Invoke a Lambda function by providing the physical ID as a resource ID:**

The physical ID gets created when you deploy using CloudFormation.

```
$ sam remote invoke sam-app-HelloWorldFunction-TZvxQRFNv0k4
```

**Invoke a Lambda function of a child stack:**

For this example, our application contains the following directory structure:

```
lambda-example
├── childstack
│   ├── function
│   │   ├── __init__.py
│   │   ├── app.py
│   │   └── requirements.txt
│   └── template.yaml
├── events
│   └── event.json
├── samconfig.toml
└── template.yaml
```

To invoke the Lambda function of our `childstack`, we run the following:

```
$ sam remote invoke ChildStack/HelloWorldFunction --stack-name lambda-example

Invoking Lambda Function HelloWorldFunction                                                                     
START RequestId: 207a864b-e67c-4307-8478-365b004d4bcd Version: $LATEST
END RequestId: 207a864b-e67c-4307-8478-365b004d4bcd
REPORT RequestId: 207a864b-e67c-4307-8478-365b004d4bcd  Duration: 1.27 ms       Billed Duration: 2 ms   Memory Size: 128 MB     Max Memory Used: 36 MB  Init Duration: 111.07 ms
{"statusCode": 200, "body": "{\"message\": \"Hello\", \"received_event\": {}}"}%
```

#### Invoke a Lambda function configured to stream responses
<a name="using-sam-cli-remote-invoke-examples-lambda-stream"></a>

In this example, we use the AWS SAM CLI to initialize a new serverless application that contains a Lambda function configured to stream its response. We deploy our application to the AWS Cloud and use the `sam remote invoke` to interact with our function in the cloud.

We start by running the `sam init` command to create a new serverless application. We select the **Lambda Response Streaming** quick start template and name our application **lambda-streaming-nodejs-app**.

```
$ sam init
	
	You can preselect a particular runtime or package type when using the `sam init` experience.
	Call `sam init --help` to learn more.
	
	Which template source would you like to use?
	        1 - AWS Quick Start Templates
	        2 - Custom Template Location
	Choice: 1
	
	Choose an AWS Quick Start application template
	        1 - Hello World Example
	        ...
	        9 - Lambda Response Streaming
	        ...
	        15 - Machine Learning
	Template: 9
	
	Which runtime would you like to use?
	        1 - go (provided.al2)
	        2 - nodejs18.x
	        3 - nodejs16.x
	Runtime: 2
	
	Based on your selections, the only Package type available is Zip.
	We will proceed to selecting the Package type as Zip.
	
	Based on your selections, the only dependency manager available is npm.
	We will proceed copying the template using npm.
	
	Would you like to enable X-Ray tracing on the function(s) in your application?  [y/N]: ENTER
	
	Would you like to enable monitoring using CloudWatch Application Insights?
	For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: ENTER
	
	Project name [sam-app]: lambda-streaming-nodejs-app
	
	    -----------------------
	    Generating application:
	    -----------------------
	    Name: lambda-streaming-nodejs-app
	    Runtime: nodejs18.x
	    Architectures: x86_64
	    Dependency Manager: npm
	    Application Template: response-streaming
	    Output Directory: .
	    Configuration file: lambda-streaming-nodejs-app/samconfig.toml
	    
	    Next steps can be found in the README file at lambda-streaming-nodejs-app/README.md
	        
	
	Commands you can use next
	=========================
	[*] Create pipeline: cd lambda-streaming-nodejs-app && sam pipeline init --bootstrap
	[*] Validate SAM template: cd lambda-streaming-nodejs-app && sam validate
	[*] Test Function in the Cloud: cd lambda-streaming-nodejs-app && sam sync --stack-name {stack-name} --watch
```

The AWS SAM CLI creates our project with the following structure:

```
lambda-streaming-nodejs-app
	├── README.md
	├── __tests__
	│   └── unit
	│       └── index.test.js
	├── package.json
	├── samconfig.toml
	├── src
	│   └── index.js
	└── template.yaml
```

The following is an example of our Lambda function code:

```
exports.handler = awslambda.streamifyResponse(
	  async (event, responseStream, context) => {
	    const httpResponseMetadata = {
	      statusCode: 200,
	      headers: {
	        "Content-Type": "text/html",
	        "X-Custom-Header": "Example-Custom-Header"
	      }
	    };
	
	    responseStream = awslambda.HttpResponseStream.from(responseStream, httpResponseMetadata);
	    // It's recommended to use a `pipeline` over the `write` method for more complex use cases.
	    // Learn more: https://docs.aws.amazon.com/lambda/latest/dg/configuration-response-streaming.html
	    responseStream.write("<html>");
	    responseStream.write("<p>First write!</p>");
	
	    responseStream.write("<h1>Streaming h1</h1>");
	    await new Promise(r => setTimeout(r, 1000));
	    responseStream.write("<h2>Streaming h2</h2>");
	    await new Promise(r => setTimeout(r, 1000));
	    responseStream.write("<h3>Streaming h3</h3>");
	    await new Promise(r => setTimeout(r, 1000));
	
	    // Long strings will be streamed
	    const loremIpsum1 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae mi tincidunt tellus ultricies dignissim id et diam. Morbi pharetra eu nisi et finibus. Vivamus diam nulla, vulputate et nisl cursus, pellentesque vehicula libero. Cras imperdiet lorem ante, non posuere dolor sollicitudin a. Vestibulum ipsum lacus, blandit nec augue id, lobortis dictum urna. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Morbi auctor orci eget tellus aliquam, non maximus massa porta. In diam ante, pulvinar aliquam nisl non, elementum hendrerit sapien. Vestibulum massa nunc, mattis non congue vitae, placerat in quam. Nam vulputate lectus metus, et dignissim erat varius a.";
	    responseStream.write(`<p>${loremIpsum1}</p>`);
	    await new Promise(r => setTimeout(r, 1000));
	
	    responseStream.write("<p>DONE!</p>");
	    responseStream.write("</html>");
	    responseStream.end();
	  }
	);
```

The following is an example of our `template.yaml` file. Response streaming for our Lambda function is configured using the `FunctionUrlConfig` property.

```
AWSTemplateFormatVersion: '2010-09-09'
	Transform: AWS::Serverless-2016-10-31
	
	Description: >
	  Sample SAM Template for lambda-streaming-nodejs-app
	  
	Resources:
	  StreamingFunction:
	    Type: AWS::Serverless::Function
	    Properties:
	      CodeUri: src/
	      Handler: index.handler
	      Runtime: nodejs18.x
	      Architectures:
	        - x86_64
	      Timeout: 10
	      FunctionUrlConfig:
	        AuthType: AWS_IAM
	        InvokeMode: RESPONSE_STREAM
	
	Outputs:
	  StreamingFunction:
	    Description: "Streaming Lambda Function ARN"
	    Value: !GetAtt StreamingFunction.Arn
	  StreamingFunctionURL:
	    Description: "Streaming Lambda Function URL"
	    Value: !GetAtt StreamingFunctionUrl.FunctionUrl
```

Typically, you can use `sam build` and `sam deploy --guided` to build and deploy a production application. In this example, we’ll assume a development environment and use the `sam sync` command to build and deploy our application.

**Note**  
The `sam sync` command is recommended for development environments. To learn more, see [Introduction to using sam sync to sync to AWS Cloud](using-sam-cli-sync.md).

Before running `sam sync`, we verify that our project is configured correctly in our `samconfig.toml` file. Most importantly, we verify the values for `stack_name` and `watch`. With these values specified in our configuration file, we don't have to provide them at the command line.

```
version = 0.1
	
	[default]
	[default.global.parameters]
	stack_name = "lambda-streaming-nodejs-app"
	
	[default.build.parameters]
	cached = true
	parallel = true
	
	[default.validate.parameters]
	lint = true
	
	[default.deploy.parameters]
	capabilities = "CAPABILITY_IAM"
	confirm_changeset = true
	resolve_s3 = true
	s3_prefix = "lambda-streaming-nodejs-app"
	region = "us-west-2"
	image_repositories = []
	
	[default.package.parameters]
	resolve_s3 = true
	
	[default.sync.parameters]
	watch = true
	
	[default.local_start_api.parameters]
	warm_containers = "EAGER"
	
	[default.local_start_lambda.parameters]
	warm_containers = "EAGER"
```

Next, we run `sam sync` to build and deploy our application. Since the `--watch` option is configured in our configuration file, the AWS SAM CLI will build our application, deploy our application, and watch for changes.

```
$ sam sync
	
	The SAM CLI will use the AWS Lambda, Amazon API Gateway, and AWS StepFunctions APIs to upload your code   
	without                                                                                                   
	performing a CloudFormation deployment. This will cause drift in your CloudFormation stack.               
	**The sync command should only be used against a development stack**.                                     
	                                                                                                          
	Queued infra sync. Waiting for in progress code syncs to complete...                                      
	Starting infra sync.                                                                                      
	Building codeuri:                                                                                         
	/Users/.../lambda-streaming-nodejs-app/src runtime: nodejs18.x metadata: {} architecture: x86_64 functions: StreamingFunction  
	package.json file not found. Continuing the build without dependencies.                                   
	Running NodejsNpmBuilder:CopySource                                                                       
	
	Build Succeeded
	
	Successfully packaged artifacts and wrote output template to file /var/folders/45/5ct135bx3fn2551_ptl5g6_80000gr/T/tmpavrzdhgp.
	Execute the following command to deploy the packaged template
	sam deploy --template-file /var/folders/45/5ct135bx3fn2551_ptl5g6_80000gr/T/tmpavrzdhgp --stack-name <YOUR STACK NAME>
	
	
	        Deploying with following values
	        ===============================
	        Stack name                   : lambda-streaming-nodejs-app
	        Region                       : us-west-2
	        Disable rollback             : False
	        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisam-s3-demo-bucket-1a4x26zbcdkqr
	        Capabilities                 : ["CAPABILITY_NAMED_IAM", "CAPABILITY_AUTO_EXPAND"]
	        Parameter overrides          : {}
	        Signing Profiles             : null
	
	Initiating deployment
	=====================
	
	
	2023-06-20 12:11:16 - Waiting for stack create/update to complete
	
	CloudFormation events from stack operations (refresh every 0.5 seconds)
	-----------------------------------------------------------------------------------------------------
	ResourceStatus            ResourceType              LogicalResourceId         ResourceStatusReason    
	-----------------------------------------------------------------------------------------------------
	CREATE_IN_PROGRESS        AWS::CloudFormation::St   lambda-streaming-         Transformation          
	                          ack                       nodejs-app                succeeded               
	CREATE_IN_PROGRESS        AWS::IAM::Role            StreamingFunctionRole     -                       
	CREATE_IN_PROGRESS        AWS::CloudFormation::St   AwsSamAutoDependencyLay   -                       
	                          ack                       erNestedStack                                     
	CREATE_IN_PROGRESS        AWS::IAM::Role            StreamingFunctionRole     Resource creation       
	                                                                              Initiated               
	CREATE_IN_PROGRESS        AWS::CloudFormation::St   AwsSamAutoDependencyLay   Resource creation       
	                          ack                       erNestedStack             Initiated               
	CREATE_COMPLETE           AWS::IAM::Role            StreamingFunctionRole     -                       
	CREATE_COMPLETE           AWS::CloudFormation::St   AwsSamAutoDependencyLay   -                       
	                          ack                       erNestedStack                                     
	CREATE_IN_PROGRESS        AWS::Lambda::Function     StreamingFunction         -                       
	CREATE_IN_PROGRESS        AWS::Lambda::Function     StreamingFunction         Resource creation       
	                                                                              Initiated               
	CREATE_COMPLETE           AWS::Lambda::Function     StreamingFunction         -                       
	CREATE_IN_PROGRESS        AWS::Lambda::Url          StreamingFunctionUrl      -                       
	CREATE_IN_PROGRESS        AWS::Lambda::Url          StreamingFunctionUrl      Resource creation       
	                                                                              Initiated               
	CREATE_COMPLETE           AWS::Lambda::Url          StreamingFunctionUrl      -                       
	CREATE_COMPLETE           AWS::CloudFormation::St   lambda-streaming-         -                       
	                          ack                       nodejs-app                                        
	-----------------------------------------------------------------------------------------------------
	
	CloudFormation outputs from deployed stack
	-------------------------------------------------------------------------------------------------------
	Outputs                                                                                               
	-------------------------------------------------------------------------------------------------------
	Key                 StreamingFunction                                                                 
	Description         Streaming Lambda Function ARN                                                     
	Value               arn:aws:lambda:us-west-2:012345678910:function:lambda-streaming-nodejs-app-       
	StreamingFunction-gUmhO833A0vZ                                                                        
	
	Key                 StreamingFunctionURL                                                              
	Description         Streaming Lambda Function URL                                                     
	Value               https://wxgkcc2dyntgtrwhf2dgdcvylu0rnnof.lambda-url.us-west-2.on.aws/             
	-------------------------------------------------------------------------------------------------------
	
	                                                                                                          
	Stack creation succeeded. Sync infra completed.                                                           
	                                                                                                          
	Infra sync completed.
```

Now that our function is deployed to the cloud, we can use `sam remote invoke` to interact with our function. The AWS SAM CLI automatically detects that our function is configured for response streaming and immediately begins outputting a streamed response of our function in real time.

```
$ sam remote invoke StreamingFunction
	
	Invoking Lambda Function StreamingFunction                                              
	{"statusCode":200,"headers":{"Content-Type":"text/html","X-Custom-Header":"Example-Custom-Header"}}<html><p>First write!</p><h1>Streaming h1</h1><h2>Streaming h2</h2><h3>Streaming h3</h3><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae mi tincidunt tellus ultricies dignissim id et diam. Morbi pharetra eu nisi et finibus. Vivamus diam nulla, vulputate et nisl cursus, pellentesque vehicula libero. Cras imperdiet lorem ante, non posuere dolor sollicitudin a. Vestibulum ipsum lacus, blandit nec augue id, lobortis dictum urna. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Morbi auctor orci eget tellus aliquam, non maximus massa porta. In diam ante, pulvinar aliquam nisl non, elementum hendrerit sapien. Vestibulum massa nunc, mattis non congue vitae, placerat in quam. Nam vulputate lectus metus, et dignissim erat varius a.</p><p>DONE!</p></html>START RequestId: 1e4cdf04-60de-4769-b3a2-c1481982deb4 Version: $LATEST
	END RequestId: 1e4cdf04-60de-4769-b3a2-c1481982deb4
	REPORT RequestId: 1e4cdf04-60de-4769-b3a2-c1481982deb4  Duration: 4088.66 ms    Billed Duration: 4089 ms        Memory Size: 128 MB     Max Memory Used: 68 MB  Init Duration: 168.45 ms
```

When we modify our function code, the AWS SAM CLI instantly detects and immediately deploys our changes. Here is an example of the AWS SAM CLI output after changes are made to our function code:

```
Syncing Lambda Function StreamingFunction...                                             
	Building codeuri:                                                                        
	/Users/.../lambda-streaming-nodejs-app/src runtime: nodejs18.x metadata: {} architecture:    
	x86_64 functions: StreamingFunction                                                      
	package.json file not found. Continuing the build without dependencies.                  
	Running NodejsNpmBuilder:CopySource                                                      
	Finished syncing Lambda Function StreamingFunction.                                      
	Syncing Layer StreamingFunctione9cfe924DepLayer...                                       
	SyncFlow [Layer StreamingFunctione9cfe924DepLayer]: Skipping resource update as the      
	content didn't change                                                                    
	Finished syncing Layer StreamingFunctione9cfe924DepLayer.
```

We can now use `sam remote invoke` again to interact with our function in the cloud and test our changes.

### SQS examples
<a name="using-sam-cli-remote-invoke-examples-sqs"></a>

#### Basic examples
<a name="using-sam-cli-remote-invoke-examples-sqs-basic"></a>

**Invoke an Amazon SQS queue by providing the ARN as a resource ID:**

```
$ sam remote invoke arn:aws:sqs:us-west-2:01234567890:sqs-example-4DonhBsjsW1b --event '{"hello": "world"}' --output json

Sending message to SQS queue MySqsQueue                                                                         
{
  "MD5OfMessageBody": "49dfdd54b01cbcd2d2ab5e9e5ee6b9b9",
  "MessageId": "4f464cdd-15ef-4b57-bd72-3ad225d80adc",
  "ResponseMetadata": {
    "RequestId": "95d39377-8323-5ef0-9223-ceb198bd09bd",
    "HTTPStatusCode": 200,
    "HTTPHeaders": {
      "x-amzn-requestid": "95d39377-8323-5ef0-9223-ceb198bd09bd",
      "date": "Wed, 08 Nov 2023 23:27:26 GMT",
      "content-type": "application/x-amz-json-1.0",
      "content-length": "106",
      "connection": "keep-alive"
    },
    "RetryAttempts": 0
  }
}%
```

### Step Functions examples
<a name="using-sam-cli-remote-invoke-examples-sf"></a>

#### Basic examples
<a name="using-sam-cli-remote-invoke-examples-sf-basic"></a>

**Invoke a state machine by providing its physical ID as a resource ID:**

First, we use `sam list resources` to obtain our physical ID:

```
$ sam list resources --stack-name state-machine-example --output json

[
  {
    "LogicalResourceId": "HelloWorldStateMachine",
    "PhysicalResourceId": "arn:aws:states:us-west-2:513423067560:stateMachine:HelloWorldStateMachine-z69tFEUx0F66"
  },
  {
    "LogicalResourceId": "HelloWorldStateMachineRole",
    "PhysicalResourceId": "simple-state-machine-HelloWorldStateMachineRole-PduA0BDGuFXw"
  }
]
```

Next, we invoke our state machine using the physical ID as a resource ID. We pass in an event at the command line with the `--event` option:

```
$ sam remote invoke arn:aws:states:us-west-2:01234567890:stateMachine:HelloWorldStateMachine-z69tFEUx0F66 --event '{"is_developer": true}'

Invoking Step Function arn:aws:states:us-west-2:01234567890:stateMachine:HelloWorldStateMachine-z69tFEUx0F66   
"Hello Developer World"%
```

**Invoke a state machine by passing an empty event:**

```
$ sam remote invoke HelloWorldStateMachine --stack-name state-machine-example

Invoking Step Function HelloWorldStateMachine                                                                   
"Hello World"%
```

## Related links
<a name="using-sam-cli-remote-invoke-links"></a>

For documentation related to `sam remote invoke` and using the AWS SAM CLI, see the following:
+ [sam remote invoke](sam-cli-command-reference-remote-invoke.md)
+ [AWS SAM CLI troubleshooting](sam-cli-troubleshooting.md)

# Automate local integration tests with AWS SAM
<a name="serverless-sam-cli-using-automated-tests"></a>

While you can use [Introduction to testing with sam local invoke](using-sam-cli-local-invoke.md) to manually test code, AWS SAM also lets you test your code using automated integration testing. Integration testing helps you detect issues early in the development cycle, improve the quality of your code, and save time while reducing costs.

To author automated integration tests in AWS SAM, you first run tests against local Lambda functions before deploying to the AWS Cloud. The [Introduction to testing with sam local start-lambda](using-sam-cli-local-start-lambda.md) command starts a local endpoint that emulates the Lambda invoke endpoint. You can invoke it from your automated tests. Because this endpoint emulates the Lambda invoke endpoint, you can write tests once, and then run them (without any modifications) against the local Lambda function, or against a deployed Lambda function. You can also run the same tests against a deployed AWS SAM stack in your CI/CD pipeline. 

This is how the process works:

1. Start the local Lambda endpoint.

   Start the local Lambda endpoint by running the following command in the directory that contains your AWS SAM template:

   ```
   sam local start-lambda
   ```

   This command starts a local endpoint at `http://127.0.0.1:3001` that emulates AWS Lambda. You can run your automated tests against this local Lambda endpoint. When you invoke this endpoint using the AWS CLI or SDK, it locally executes the Lambda function that's specified in the request, and returns a response.

1. Run an integration test against the local Lambda endpoint.

   In your integration test, you can use the AWS SDK to invoke your Lambda function with test data, wait for response, and verify that the response is what you expect. To run the integration test locally, you should configure the AWS SDK to send a Lambda Invoke API call to invoke the local Lambda endpoint that you started in previous step.

   The following is a Python example (the AWS SDKs for other languages have similar configurations):

   ```
   import boto3
   import botocore
   
   # Set "running_locally" flag if you are running the integration test locally
   running_locally = True
   
   if running_locally:
   
       # Create Lambda SDK client to connect to appropriate Lambda endpoint
       lambda_client = boto3.client('lambda',
           region_name="us-west-2",
           endpoint_url="http://127.0.0.1:3001",
           use_ssl=False,
           verify=False,
           config=botocore.client.Config(
               signature_version=botocore.UNSIGNED,
               read_timeout=15,
               retries={'max_attempts': 0},
           )
       )
   else:
       lambda_client = boto3.client('lambda')
   
   
   # Invoke your Lambda function as you normally usually do. The function will run
   # locally if it is configured to do so
   response = lambda_client.invoke(FunctionName="HelloWorldFunction")
   
   # Verify the response
   assert response == "Hello World"
   ```

   You can use this code to test deployed Lambda functions by setting `running_locally` to `False`. This sets up the AWS SDK to connect to AWS Lambda in the AWS Cloud.

# Generate sample event payloads with AWS SAM
<a name="serverless-sam-cli-using-generate-event"></a>

To test your Lambda functions, you can generate and customize sample event payloads that imitate the data your Lambda functions will receive when triggered by other AWS services. This includes services like API Gateway, CloudFormation, Amazon S3, and more.

Generating sample event payloads helps you test the behavior of your Lambda function with a variety of different inputs without needing to work in a live environment. This approach also saves time when compared to manually creating AWS service event samples to test functions. 

For the full list of services that you can generate sample event payloads for, use this command:

```
sam local generate-event --help
```

For the list of options you can use for a particular service, use this command:

```
sam local generate-event [SERVICE] --help
```

Examples:

```
#Generates the event from S3 when a new object is created
sam local generate-event s3 put

# Generates the event from S3 when an object is deleted
sam local generate-event s3 delete
```

# Testing and debugging durable functions
<a name="test-and-debug-durable-functions"></a>

Testing and debugging durable functions locally works similarly to regular Lambda functions, with automatic support for checkpointing and replay. This guide covers common testing scenarios and troubleshooting techniques.

## Local testing workflow
<a name="test-and-debug-durable-functions-workflow"></a>

When testing durable functions locally, the workflow differs from regular Lambda functions:

**Durable function testing workflow**

1. Build your application:

   ```
   $ sam build
   ```

1. Invoke your durable function:

   ```
   $ sam local invoke MyDurableFunction --durable-execution-name test 
   ```

1. Check execution history if needed:

   ```
   $ sam local execution history execution-id
   ```

## Common testing scenarios
<a name="test-and-debug-durable-functions-scenarios"></a>

### Testing checkpointing behavior
<a name="test-and-debug-durable-functions-scenarios-checkpoints"></a>

To test that your function properly checkpoints state:

```
# Example Python durable function
def handler(event, context):
    # This will create a checkpoint
    context.wait(10)  # Wait 10 seconds
    
    # Function resumes here after wait
    return {"message": "Function resumed after wait"}
```

When you invoke this function locally, the wait period is handled automatically.

### Testing callback scenarios
<a name="test-and-debug-durable-functions-scenarios-callbacks"></a>

For functions that wait for external callbacks:

1. Start your durable function that waits for a callback

1. In another terminal, resolve the callback:

   ```
   $ sam local callback succeed callback-id
   ```

1. Observe the function resume execution

## Troubleshooting
<a name="test-and-debug-durable-functions-troubleshooting"></a>

### Durable function not executing properly
<a name="test-and-debug-durable-functions-troubleshooting-config"></a>

**Problem:** The function doesn't behave as a durable function.

**Solutions:**
+ Verify that `DurableConfig` is set in your SAM template
+ Ensure your function code uses durable function SDK methods (e.g., `context.wait()`)
+ Check that you're using a supported runtime (TypeScript, JavaScript, Python)

### Cannot retrieve execution history
<a name="test-and-debug-durable-functions-troubleshooting-history"></a>

**Problem:** The `local execution history` command returns no results.

**Solutions:**
+ Verify the execution ID is correct
+ Check that the function has been invoked at least once

### Callback commands not working
<a name="test-and-debug-durable-functions-troubleshooting-callbacks"></a>

**Problem:** Callback commands don't resolve pending operations.

**Solutions:**
+ Verify the callback ID is correct
+ Ensure the function is actually waiting for a callback
+ Verify you're using the correct callback command syntax

## Debugging tips
<a name="test-and-debug-durable-functions-debugging"></a>
+ **Use execution history** - Review execution history to understand the flow of your durable function
+ **Test incrementally** - Start with simple wait operations before adding complex logic
+ **Use verbose logging** - Enable detailed logging to trace execution flow

## Learn more
<a name="test-and-debug-durable-functions-learn"></a>

For more information about testing and debugging, see:
+ [Introduction to testing with sam local invoke](using-sam-cli-local-invoke.md) - Local invoke documentation
+ [sam local execution history](sam-cli-command-reference-sam-local-execution-history.md) - Execution history