Skip to content

Commit f6ecd71

Browse files
authored
Merge pull request #2397 from aws-samples/ide/apigw-rest-api-lambda-node
New pattern - REST API Hello World (Node)
2 parents fb86a87 + ece6dca commit f6ecd71

File tree

7 files changed

+396
-0
lines changed

7 files changed

+396
-0
lines changed
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
# Hello World AWS Lambda and Amazon API Gateway REST API
2+
3+
This project contains source code and supporting files for a serverless application that you can deploy with the AWS SAM CLI. It includes the following files and folders.
4+
5+
- hello_world - Code for the application's Lambda function.
6+
- events - Invocation events that you can use to invoke the function.
7+
- template.yaml - A template that defines the application's AWS resources.
8+
9+
The application uses several AWS resources. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code. This application will deploy a Lambda function, as well as an API Gateway REST API that will be automatically created based on the Lambda function's Event mapping.
10+
11+
If you prefer to use an integrated development environment (IDE) to build and test your application, you can use the AWS Toolkit.
12+
The AWS Toolkit is an open source plug-in for popular IDEs that uses the AWS SAM CLI to build and deploy serverless applications on AWS. The AWS Toolkit also adds a simplified step-through debugging experience for Lambda function code. See the following links to get started.
13+
14+
* [CLion](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
15+
* [GoLand](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
16+
* [IntelliJ](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
17+
* [WebStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
18+
* [Rider](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
19+
* [PhpStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
20+
* [PyCharm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
21+
* [RubyMine](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
22+
* [DataGrip](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
23+
* [VS Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html)
24+
* [Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html)
25+
26+
## Deploy the sample application
27+
28+
The Serverless Application Model Command Line Interface (SAM CLI) is an extension of the AWS CLI that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API.
29+
30+
To use the AWS SAM CLI, you need the following tools.
31+
32+
### Requirements
33+
34+
* AWS SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)
35+
* [NodeJS 20 installed](https://nodejs.org/en/download/)
36+
* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community)
37+
38+
To build and deploy your application for the first time, run the following in your shell:
39+
40+
```bash
41+
$ cd apigw-rest-api-lambda-node
42+
$ sam build --use-container
43+
$ sam deploy --guided
44+
```
45+
46+
The first command will build the source of your application. The second command will package and deploy your application to AWS, with a series of prompts:
47+
48+
* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name.
49+
* **AWS Region**: The AWS region you want to deploy your app to.
50+
* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes.
51+
* **HelloWorldFunction has no authentication. Is this okay? [y/N]:**: Select `y` for the purposes of this sample application. As a result, anyone will be able to call this example REST API without any form of authentication. For production applications, you should [enable authentication for the API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-to-api.html) using one of several available options and [follow the API Gateway security best practices](https://docs.aws.amazon.com/apigateway/latest/developerguide/security-best-practices.html). If `N` is selected for this question, this deployment will not succeed.
52+
* **Allow AWS SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command.
53+
* **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application.
54+
55+
You can find your API Gateway Endpoint URL in the output values displayed after deployment.
56+
57+
## Use the AWS SAM CLI to test locally
58+
59+
The SAM CLI installs dependencies defined in `hello_world/package.json`, creates a deployment package, and saves it in the `.aws-sam/build` folder.
60+
61+
Ypu can test a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the `events` folder in this project.
62+
63+
Run functions locally and invoke them with the `sam local invoke` command.
64+
65+
```bash
66+
$ sam local invoke HelloWorldFunction --event events/event.json
67+
```
68+
69+
The AWS SAM CLI can also emulate your application's API. Use the `sam local start-api` to run the API locally on port 3000.
70+
71+
```bash
72+
$ sam local start-api
73+
$ curl http://localhost:3000/
74+
```
75+
76+
The AWS SAM CLI reads the application template to determine the API's routes and the functions they invoke. The `Events` property on each function's definition includes the route and method for each path.
77+
78+
```yaml
79+
Events:
80+
HelloWorld:
81+
Type: Api
82+
Properties:
83+
Path: /hello
84+
Method: get
85+
```
86+
87+
## Use the AWS SAM CLI to test remotely
88+
After you have deployed your application, you can remotely invoke your Lambda function to test it in the cloud.
89+
90+
Invoke functions remotely with the `sam remote invoke` command.
91+
92+
```bash
93+
$ sam remote invoke HelloWorldFunction --event-file events/event.json
94+
```
95+
96+
You can also go to the API Gateway endpoint URL that was output after the deployment of your application, which will similarly invoke your deployed Lambda function.
97+
98+
## Fetch, tail, and filter Lambda function logs
99+
To simplify troubleshooting, AWS SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug.
100+
101+
`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using AWS SAM.
102+
103+
```bash
104+
$ sam logs -n HelloWorldFunction --stack-name "YOUR_STACK_NAME_HERE" --tail
105+
```
106+
107+
You can find more information and examples about filtering Lambda function logs in the [AWS SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html).
108+
109+
110+
## Cleanup
111+
112+
To delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack name, you can run the following:
113+
114+
```bash
115+
$ sam delete
116+
```
117+
118+
## Resources
119+
120+
See the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) for an introduction to SAM specification, the SAM CLI, and serverless application concepts.
121+
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
{
2+
"title": "Hello World AWS Lambda and Amazon API Gateway REST API",
3+
"description": "Create a simple Lambda function connected to a REST API.",
4+
"language": "Node.js",
5+
"level": "200",
6+
"framework": "SAM",
7+
"introBox": {
8+
"headline": "How it works",
9+
"text": [
10+
"This sample project demonstrates how to invoke a simple Lambda function using a REST API.",
11+
"This pattern deploys one Lambda Function, and one API Gateway REST API."
12+
]
13+
},
14+
"gitHub": {
15+
"template": {
16+
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-rest-api-lambda-node",
17+
"templateURL": "serverless-patterns/apigw-rest-api-lambda-node",
18+
"projectFolder": "apigw-rest-api-lambda-node",
19+
"templateFile": "template.yaml"
20+
}
21+
},
22+
"resources": {
23+
"bullets": [
24+
{
25+
"text": "Invoke Lambda with a REST API",
26+
"link": "https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html"
27+
},
28+
{
29+
"text": "Amazon API Gateway REST API",
30+
"link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-rest-api.html"
31+
}
32+
]
33+
},
34+
"deploy": {
35+
"text": [
36+
"sam deploy --guided"
37+
]
38+
},
39+
"testing": {
40+
"text": [
41+
"See the GitHub repo for detailed testing instructions."
42+
]
43+
},
44+
"cleanup": {
45+
"text": [
46+
"Delete the application: <code>sam delete</code>."
47+
]
48+
},
49+
"authors": [
50+
{
51+
"name": "Seshu Brahma",
52+
"image": "https://i.postimg.cc/ZR0MyrTN/seshub-photo.jpg",
53+
"bio": "SDE II, Lambda, AWS",
54+
"linkedin": "seshu-brahma"
55+
}
56+
],
57+
"patternArch": {
58+
"icon1": {
59+
"x": 20,
60+
"y": 50,
61+
"service": "apigw",
62+
"label": "API Gateway REST API"
63+
},
64+
"icon2": {
65+
"x": 80,
66+
"y": 50,
67+
"service": "lambda",
68+
"label": "AWS Lambda"
69+
},
70+
"line1": {
71+
"from": "icon1",
72+
"to": "icon2",
73+
"label": "Request"
74+
}
75+
}
76+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
{
2+
"body": "{\"message\": \"hello world\"}",
3+
"resource": "/{proxy+}",
4+
"path": "/path/to/resource",
5+
"httpMethod": "POST",
6+
"isBase64Encoded": false,
7+
"queryStringParameters": {
8+
"foo": "bar"
9+
},
10+
"pathParameters": {
11+
"proxy": "/path/to/resource"
12+
},
13+
"stageVariables": {
14+
"baz": "qux"
15+
},
16+
"headers": {
17+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
18+
"Accept-Encoding": "gzip, deflate, sdch",
19+
"Accept-Language": "en-US,en;q=0.8",
20+
"Cache-Control": "max-age=0",
21+
"CloudFront-Forwarded-Proto": "https",
22+
"CloudFront-Is-Desktop-Viewer": "true",
23+
"CloudFront-Is-Mobile-Viewer": "false",
24+
"CloudFront-Is-SmartTV-Viewer": "false",
25+
"CloudFront-Is-Tablet-Viewer": "false",
26+
"CloudFront-Viewer-Country": "US",
27+
"Host": "1234567890.execute-api.us-east-1.amazonaws.com",
28+
"Upgrade-Insecure-Requests": "1",
29+
"User-Agent": "Custom User Agent String",
30+
"Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)",
31+
"X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==",
32+
"X-Forwarded-For": "127.0.0.1, 127.0.0.2",
33+
"X-Forwarded-Port": "443",
34+
"X-Forwarded-Proto": "https"
35+
},
36+
"requestContext": {
37+
"accountId": "123456789012",
38+
"resourceId": "123456",
39+
"stage": "prod",
40+
"requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
41+
"requestTime": "09/Apr/2015:12:34:56 +0000",
42+
"requestTimeEpoch": 1428582896000,
43+
"identity": {
44+
"cognitoIdentityPoolId": null,
45+
"accountId": null,
46+
"cognitoIdentityId": null,
47+
"caller": null,
48+
"accessKey": null,
49+
"sourceIp": "127.0.0.1",
50+
"cognitoAuthenticationType": null,
51+
"cognitoAuthenticationProvider": null,
52+
"userArn": null,
53+
"userAgent": "Custom User Agent String",
54+
"user": null
55+
},
56+
"path": "/prod/path/to/resource",
57+
"resourcePath": "/{proxy+}",
58+
"httpMethod": "POST",
59+
"apiId": "1234567890",
60+
"protocol": "HTTP/1.1"
61+
}
62+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
{
2+
"title": "Hello World AWS Lambda and Amazon API Gateway REST API",
3+
"description": "Create a simple Lambda Function connected to a REST API.",
4+
"language": "Node",
5+
"level": "200",
6+
"framework": "SAM",
7+
"introBox": {
8+
"headline": "How it works",
9+
"text": [
10+
"This sample project demonstrates how to trigger a simple Lambda function using a REST API.",
11+
"This pattern deploys one Lambda Function, andn one API Gateway REST API."
12+
]
13+
},
14+
"gitHub": {
15+
"template": {
16+
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-rest-api-lambda-node",
17+
"templateURL": "serverless-patterns/apigw-rest-api-lambda-node",
18+
"projectFolder": "apigw-rest-api-lambda-node",
19+
"templateFile": "template.yaml"
20+
}
21+
},
22+
"resources": {
23+
"bullets": [
24+
{
25+
"text": "Trigger Lambda with a REST API",
26+
"link": "https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html"
27+
},
28+
{
29+
"text": "Amazon API Gateway REST API",
30+
"link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-rest-api.html"
31+
}
32+
]
33+
},
34+
"deploy": {
35+
"text": [
36+
"sam deploy --guided"
37+
]
38+
},
39+
"testing": {
40+
"text": [
41+
"See the GitHub repo for detailed testing instructions."
42+
]
43+
},
44+
"cleanup": {
45+
"text": [
46+
"Delete the application: <code>sam delete</code>."
47+
]
48+
},
49+
"authors": [
50+
{
51+
"name": "Seshu Brahma",
52+
"image": "https://i.postimg.cc/ZR0MyrTN/seshub-photo.jpg",
53+
"bio": "SDE for AWS Lambda",
54+
"linkedin": "seshu-brahma"
55+
}
56+
]
57+
}
58+
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
*
3+
* Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format
4+
* @param {Object} event - API Gateway Lambda Proxy Input Format
5+
*
6+
* Context doc: https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html
7+
* @param {Object} context
8+
*
9+
* Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
10+
* @returns {Object} object - API Gateway Lambda Proxy Output Format
11+
*
12+
*/
13+
14+
export const lambdaHandler = async (event, context) => {
15+
const response = {
16+
statusCode: 200,
17+
body: JSON.stringify({
18+
message: 'hello world',
19+
})
20+
};
21+
22+
return response;
23+
};
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"name": "hello_world",
3+
"version": "1.0.0",
4+
"description": "hello world sample for NodeJS",
5+
"main": "app.js",
6+
"repository": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-rest-api-lambda-node",
7+
"author": "SAM CLI",
8+
"license": "MIT",
9+
"dependencies": {
10+
"axios": ">=1.6.0"
11+
},
12+
"devDependencies": {
13+
"chai": "^4.3.6",
14+
"mocha": "^10.2.0"
15+
}
16+
}

0 commit comments

Comments
 (0)