Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions apigw-http-api-lambda-rust/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[package]
name = "apigw-http-api-lambda-rust"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[[bin]]
name = "handler"
path = "src/bin/handler.rs"

[dependencies]
lambda_http = "0.4.1"
lambda_runtime = "0.4.1"
serde_json = "1.0.68"
tokio = { version = "1", features = ["full"] }
21 changes: 21 additions & 0 deletions apigw-http-api-lambda-rust/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
FUNCTIONS := handler
ARCH := aarch64-unknown-linux-gnu

build:
cross build --release --target $(ARCH)
rm -rf ./build
mkdir -p ./build
${MAKE} ${MAKEOPTS} $(foreach function,${FUNCTIONS}, build-${function})

build-%:
mkdir -p ./build/$*
cp -v ./target/$(ARCH)/release/$* ./build/$*/bootstrap

deploy:
if [ -f samconfig.toml ]; \
then sam deploy; \
else sam deploy -g; \
fi

delete:
sam delete
94 changes: 94 additions & 0 deletions apigw-http-api-lambda-rust/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# Amazon API Gateway HTTP API to AWS Lambda

This pattern creates an Amazon API Gateway HTTP API and an AWS Lambda function.

Learn more about this pattern at [Serverless Land Patterns](https://serverlessland.com/patterns/apigw-lambda-rust).

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.

## Requirements

* [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.
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
* [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed

## Deployment Instructions

1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
```
git clone https://github.com/aws-samples/serverless-patterns
```
2. Change directory to the pattern directory:
```
cd apigw-http-api-lambda-rust
```
3. Install dependencies and build (docker and cross build are required):
```
make build
```
4. From the command line, use AWS SAM to deploy the AWS resources for the pattern as specified in the template.yml file:
```
make deploy
```
5. During the prompts:
* Enter a stack name
* Enter the desired AWS Region
* Allow SAM CLI to create IAM roles with the required permissions.

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.

6. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs which are used for testing.


## How it works

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.

## Testing

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.

Example GET Request: https://{HttpApiId}.execute-api.{region}.amazonaws.com/

Response:
```
hello stranger
```

Example POST Request: https://{HttpApiId}.execute-api.{region}.amazonaws.com/path1/path2?name=Daniele
- Request Header: "Content-Type: application/json"

Response:
```
hello Daniele
```

## Documentation
- [Working with HTTP APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api.html)
- [Working with AWS Lambda proxy integrations for HTTP APIs](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html)
- [AWS Lambda - the Basics](https://docs.aws.amazon.com/whitepapers/latest/serverless-architectures-lambda/aws-lambdathe-basics.html)
- [Lambda Function Handler](https://docs.aws.amazon.com/whitepapers/latest/serverless-architectures-lambda/the-handler.html)
- [Function Event Object - Overview](https://docs.aws.amazon.com/whitepapers/latest/serverless-architectures-lambda/the-event-object.html)
- [Function Event Object - HTTP API v2 Event](https://github.com/awsdocs/aws-lambda-developer-guide/blob/master/sample-apps/nodejs-apig/event-v2.json)
- [Function Context Object - Overview](https://docs.aws.amazon.com/whitepapers/latest/serverless-architectures-lambda/the-context-object.html)
- [Function Context Object in Node.js - Properties](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-context.html)
- [Function Environment Variables](https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html)

## Cleanup

1. Delete the stack
```bash
aws cloudformation delete-stack --stack-name STACK_NAME
```
2. Confirm the stack has been deleted
```bash
aws cloudformation list-stacks --query "StackSummaries[?contains(StackName,'STACK_NAME')].StackStatus"
```

This pattern was contributed by Greg Davis.

----
Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: MIT-0
23 changes: 23 additions & 0 deletions apigw-http-api-lambda-rust/src/bin/handler.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use lambda_http::{
handler,
lambda_runtime::{self, Context, Error},
IntoResponse, Request, RequestExt,
};

#[tokio::main]
async fn main() -> Result<(), Error> {
lambda_runtime::run(handler(|event: Request, ctx: Context| execute(event, ctx))).await?;
Ok(())
}

pub async fn execute(event: Request, _ctx: Context) -> Result<impl IntoResponse, Error> {
println!("EVENT {:?}", event);

Ok(format!(
"hello {}",
event // access information provided directly from the underlying trigger events using the RequestExt trait
.query_string_parameters()
.get("name")
.unwrap_or_else(|| "stranger")
))
}
62 changes: 62 additions & 0 deletions apigw-http-api-lambda-rust/template.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
AWSTemplateFormatVersion: 2010-09-09
Transform: 'AWS::Serverless-2016-10-31'
Description: An Amazon API Gateway HTTP API and an AWS Lambda function.

# Global values that are applied to all applicable resources in this template
Globals:
Function:
MemorySize: 128
Architectures: ["arm64"]
Handler: bootstrap
Runtime: provided.al2
Timeout: 29
Environment:
Variables:
RUST_BACKTRACE: 1
RUST_LOG: info

Parameters:
AppName:
Description: Name of Application
Type: String
Default: apigw-http-api-lambda

Resources:
##########################################################################
# API Gateway HTTP API #
##########################################################################
HttpApi:
Type: 'AWS::ApiGatewayV2::Api'
Properties:
Name: !Ref AppName
Description: An Amazon API Gateway HTTP API and an AWS Lambda function.
ProtocolType: HTTP
CorsConfiguration:
AllowOrigins:
- '*'
AllowMethods:
- GET
- HEAD
- OPTIONS
- POST
Target: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${LambdaFunction}/invocations
##########################################################################
# Lambda Function #
##########################################################################
LambdaFunction:
Type: 'AWS::Serverless::Function'
Properties:
CodeUri: ./build/handler
# Function permissions grant an AWS service or another account permission to use a function
FunctionResourcePermission:
Type: 'AWS::Lambda::Permission'
Properties:
Action: 'lambda:InvokeFunction'
Principal: apigateway.amazonaws.com
FunctionName: !Ref LambdaFunction
SourceArn: !Sub 'arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${HttpApi}/*'

Outputs:
HttpApiEndpoint:
Description: The default endpoint for the HTTP API.
Value: !GetAtt HttpApi.ApiEndpoint