Amazon Web Services (AWS) - Invoke Serverless Application Model (SAM) Lambda Function using the sam remote invoke command

by
Jeremy Canfield |
Updated: November 17 2023
| Amazon Web Services (AWS) articles
This assumes you have already:
- Downloaded and Installed the AWS Serverless Application Model (SAM) CLI on Linux.
- Initialize Serverless Application Model (SAM) app using the sam init command
- Built your Serverless Application Model (SAM) app using the sam build command
- Deployed Serverless Application Model (SAM) app using the sam deploy command
Let's say the template.yaml file for your SAM app is located at /tmp/sam-hello-world/sam-app/template.yaml.
]$ ll /tmp/sam-hello-wolrd/sam-app
total 20
drwxrwxr-x 2 ec2-user ec2-user 24 Nov 16 02:13 events
drwxrwxr-x 2 ec2-user ec2-user 63 Nov 16 02:13 hello_world
-rw-rw-r-- 1 ec2-user ec2-user 0 Nov 16 02:13 __init__.py
-rw-rw-r-- 1 ec2-user ec2-user 8329 Nov 16 02:13 README.md
-rw-rw-r-- 1 ec2-user ec2-user 679 Nov 16 02:13 samconfig.toml
-rw-rw-r-- 1 ec2-user ec2-user 1681 Nov 16 02:13 template.yaml
drwxrwxr-x 4 ec2-user ec2-user 80 Nov 16 02:13 tests
The sam list endpoints command should return both the /Prod and /Stage URLs of your Serverless Application Model (SAM) apps.
]$ sam list endpoints --template /tmp/sam-hello-world/sam-app/template.yaml --output json
[
{
"LogicalResourceId": "HelloWorldFunction",
"PhysicalResourceId": "sam-app-HelloWorldFunction-MgYCNMibayEZ",
"CloudEndpoint": "-",
"Methods": "-"
},
{
"LogicalResourceId": "ServerlessRestApi",
"PhysicalResourceId": "zulgntw90l",
"CloudEndpoint": [
"https://zulgntw90l.execute-api.us-east-1.amazonaws.com/Prod",
"https://zulgntw90l.execute-api.us-east-1.amazonaws.com/Stage"
],
"Methods": [
"/hello['get']"
]
}
]
The sam remote invoke <function> --stack-name <stack name> command can be used to invoke a Lambda function in your SAM app. Since the output above has HelloWorldFunction and sam-app, the following command would be used.
Invoking Lambda Function HelloWorldFunction
START RequestId: e482f4e8-15c0-434f-86e7-7cc846b10fec Version: $LATEST
END RequestId: e482f4e8-15c0-434f-86e7-7cc846b10fec
REPORT RequestId: e482f4e8-15c0-434f-86e7-7cc846b10fec Duration: 1.45 ms Billed Duration: 2 ms Memory Size: 128 MB Max Memory Used: 36 MB Init Duration: 109.89 ms
{"statusCode": 200, "body": "{\"message\": \"hello world\"}"}
Did you find this article helpful?
If so, consider buying me a coffee over at