Processing HTTP events with Rust
Amazon API Gateway APIs, Application Load Balancers, and Lambda function URLs can send HTTP events to Lambda. You can use
the aws_lambda_events
Example — Handle API Gateway proxy request
Note the following:
-
use aws_lambda_events::apigw::{ApiGatewayProxyRequest, ApiGatewayProxyResponse}: The aws_lambda_eventscrate includes many Lambda events. To reduce compilation time, use feature flags to activate the events you need. Example: aws_lambda_events = { version = "0.8.3", default-features = false, features = ["apigw"] }. -
use http::HeaderMap: This import requires you to add the httpcrate to your dependencies.
use aws_lambda_events::apigw::{ApiGatewayProxyRequest, ApiGatewayProxyResponse}; use http::HeaderMap; use lambda_runtime::{service_fn, Error, LambdaEvent}; async fn handler( _event: LambdaEvent<ApiGatewayProxyRequest>, ) -> Result<ApiGatewayProxyResponse, Error> { let mut headers = HeaderMap::new(); headers.insert("content-type", "text/html".parse().unwrap()); let resp = ApiGatewayProxyResponse { status_code: 200, multi_value_headers: headers.clone(), is_base64_encoded: false, body: Some("Hello AWS Lambda HTTP request".into()), headers, }; Ok(resp) } #[tokio::main] async fn main() -> Result<(), Error> { lambda_runtime::run(service_fn(handler)).await }
The Rust runtime client for Lambda
Note
The lambda_httplambda_runtime separately.
Example — Handle HTTP requests
use lambda_http::{service_fn, Error, IntoResponse, Request, RequestExt, Response}; async fn handler(event: Request) -> Result<impl IntoResponse, Error> { let resp = Response::builder() .status(200) .header("content-type", "text/html") .body("Hello AWS Lambda HTTP request") .map_err(Box::new)?; Ok(resp) } #[tokio::main] async fn main() -> Result<(), Error> { lambda_http::run(service_fn(handler)).await }
For another example of how to use lambda_http, see
the http-axum code sample
Sample HTTP Lambda events for Rust
-
Lambda HTTP events
: A Rust function that handles HTTP events. -
Lambda HTTP events with CORS headers
: A Rust function that uses Tower to inject CORS headers. -
Lambda HTTP events with shared resources
: A Rust function that uses shared resources initialized before the function handler is created.