Skip to content

Commit 5095bf5

Browse files
authored
Merge pull request #398 from ymwjbxxq/ymwjbxxq-feature-apigw-http-api-lambda-rust
New Pattern: apigw-http-api-lambda in rust
2 parents 8c0b1b6 + 4ec8f70 commit 5095bf5

File tree

5 files changed

+215
-0
lines changed

5 files changed

+215
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
[package]
2+
name = "apigw-http-api-lambda-rust"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7+
[[bin]]
8+
name = "handler"
9+
path = "src/bin/handler.rs"
10+
11+
[dependencies]
12+
lambda_http = "0.4.1"
13+
lambda_runtime = "0.4.1"
14+
serde_json = "1.0.68"
15+
tokio = { version = "1", features = ["full"] }
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
FUNCTIONS := handler
2+
ARCH := aarch64-unknown-linux-gnu
3+
4+
build:
5+
cross build --release --target $(ARCH)
6+
rm -rf ./build
7+
mkdir -p ./build
8+
${MAKE} ${MAKEOPTS} $(foreach function,${FUNCTIONS}, build-${function})
9+
10+
build-%:
11+
mkdir -p ./build/$*
12+
cp -v ./target/$(ARCH)/release/$* ./build/$*/bootstrap
13+
14+
deploy:
15+
if [ -f samconfig.toml ]; \
16+
then sam deploy; \
17+
else sam deploy -g; \
18+
fi
19+
20+
delete:
21+
sam delete
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
# Amazon API Gateway HTTP API to AWS Lambda
2+
3+
This pattern creates an Amazon API Gateway HTTP API and an AWS Lambda function.
4+
5+
Learn more about this pattern at [Serverless Land Patterns](https://serverlessland.com/patterns/apigw-lambda-rust).
6+
7+
Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example.
8+
9+
## Requirements
10+
11+
* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
12+
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
13+
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
14+
* [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed
15+
16+
## Deployment Instructions
17+
18+
1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
19+
```
20+
git clone https://github.com/aws-samples/serverless-patterns
21+
```
22+
2. Change directory to the pattern directory:
23+
```
24+
cd apigw-http-api-lambda-rust
25+
```
26+
3. Install dependencies and build (docker and cross build are required):
27+
```
28+
make build
29+
```
30+
4. From the command line, use AWS SAM to deploy the AWS resources for the pattern as specified in the template.yml file:
31+
```
32+
make deploy
33+
```
34+
5. During the prompts:
35+
* Enter a stack name
36+
* Enter the desired AWS Region
37+
* Allow SAM CLI to create IAM roles with the required permissions.
38+
39+
Once you have run `sam deploy -guided` mode once and saved arguments to a configuration file (samconfig.toml), you can use `sam deploy` in future to use these defaults.
40+
41+
6. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs which are used for testing.
42+
43+
44+
## How it works
45+
46+
This pattern deploys an Amazon API Gateway HTTP API with a default route and basic CORS configuration. The default route is integrated with an AWS Lambda function written in Node.js. The function logs the incoming API event (v2) and context object to an Amazon CloudWatch Logs log group and returns basic information about the event to the caller.
47+
48+
## Testing
49+
50+
Once the application is deployed, retrieve the HttpApiEndpoint value from CloudFormation Outputs. Either browse to the endpoint in a web browser or call the endpoint from Postman.
51+
52+
Example GET Request: https://{HttpApiId}.execute-api.{region}.amazonaws.com/
53+
54+
Response:
55+
```
56+
hello stranger
57+
```
58+
59+
Example POST Request: https://{HttpApiId}.execute-api.{region}.amazonaws.com/path1/path2?name=Daniele
60+
- Request Header: "Content-Type: application/json"
61+
62+
Response:
63+
```
64+
hello Daniele
65+
```
66+
67+
## Documentation
68+
- [Working with HTTP APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api.html)
69+
- [Working with AWS Lambda proxy integrations for HTTP APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html)
70+
- [AWS Lambda - the Basics](https://docs.aws.amazon.com/whitepapers/latest/serverless-architectures-lambda/aws-lambdathe-basics.html)
71+
- [Lambda Function Handler](https://docs.aws.amazon.com/whitepapers/latest/serverless-architectures-lambda/the-handler.html)
72+
- [Function Event Object - Overview](https://docs.aws.amazon.com/whitepapers/latest/serverless-architectures-lambda/the-event-object.html)
73+
- [Function Event Object - HTTP API v2 Event](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/nodejs-apig/event-v2.json)
74+
- [Function Context Object - Overview](https://docs.aws.amazon.com/whitepapers/latest/serverless-architectures-lambda/the-context-object.html)
75+
- [Function Context Object in Node.js - Properties](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-context.html)
76+
- [Function Environment Variables](https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html)
77+
78+
## Cleanup
79+
80+
1. Delete the stack
81+
```bash
82+
aws cloudformation delete-stack --stack-name STACK_NAME
83+
```
84+
2. Confirm the stack has been deleted
85+
```bash
86+
aws cloudformation list-stacks --query "StackSummaries[?contains(StackName,'STACK_NAME')].StackStatus"
87+
```
88+
89+
This pattern was contributed by Greg Davis.
90+
91+
----
92+
Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
93+
94+
SPDX-License-Identifier: MIT-0
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
use lambda_http::{
2+
handler,
3+
lambda_runtime::{self, Context, Error},
4+
IntoResponse, Request, RequestExt,
5+
};
6+
7+
#[tokio::main]
8+
async fn main() -> Result<(), Error> {
9+
lambda_runtime::run(handler(|event: Request, ctx: Context| execute(event, ctx))).await?;
10+
Ok(())
11+
}
12+
13+
pub async fn execute(event: Request, _ctx: Context) -> Result<impl IntoResponse, Error> {
14+
println!("EVENT {:?}", event);
15+
16+
Ok(format!(
17+
"hello {}",
18+
event // access information provided directly from the underlying trigger events using the RequestExt trait
19+
.query_string_parameters()
20+
.get("name")
21+
.unwrap_or_else(|| "stranger")
22+
))
23+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
AWSTemplateFormatVersion: 2010-09-09
2+
Transform: 'AWS::Serverless-2016-10-31'
3+
Description: An Amazon API Gateway HTTP API and an AWS Lambda function.
4+
5+
# Global values that are applied to all applicable resources in this template
6+
Globals:
7+
Function:
8+
MemorySize: 128
9+
Architectures: ["arm64"]
10+
Handler: bootstrap
11+
Runtime: provided.al2
12+
Timeout: 29
13+
Environment:
14+
Variables:
15+
RUST_BACKTRACE: 1
16+
RUST_LOG: info
17+
18+
Parameters:
19+
AppName:
20+
Description: Name of Application
21+
Type: String
22+
Default: apigw-http-api-lambda
23+
24+
Resources:
25+
##########################################################################
26+
# API Gateway HTTP API #
27+
##########################################################################
28+
HttpApi:
29+
Type: 'AWS::ApiGatewayV2::Api'
30+
Properties:
31+
Name: !Ref AppName
32+
Description: An Amazon API Gateway HTTP API and an AWS Lambda function.
33+
ProtocolType: HTTP
34+
CorsConfiguration:
35+
AllowOrigins:
36+
- '*'
37+
AllowMethods:
38+
- GET
39+
- HEAD
40+
- OPTIONS
41+
- POST
42+
Target: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${LambdaFunction}/invocations
43+
##########################################################################
44+
# Lambda Function #
45+
##########################################################################
46+
LambdaFunction:
47+
Type: 'AWS::Serverless::Function'
48+
Properties:
49+
CodeUri: ./build/handler
50+
# Function permissions grant an AWS service or another account permission to use a function
51+
FunctionResourcePermission:
52+
Type: 'AWS::Lambda::Permission'
53+
Properties:
54+
Action: 'lambda:InvokeFunction'
55+
Principal: apigateway.amazonaws.com
56+
FunctionName: !Ref LambdaFunction
57+
SourceArn: !Sub 'arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${HttpApi}/*'
58+
59+
Outputs:
60+
HttpApiEndpoint:
61+
Description: The default endpoint for the HTTP API.
62+
Value: !GetAtt HttpApi.ApiEndpoint

0 commit comments

Comments
 (0)