lambdamux is an AWS Lambda HTTP router for Rust.
It lets you write route handlers with #[route(...)] attributes and dispatch API Gateway requests without managing a global route cache yourself.
This repository also includes a Rust AWS Lambda HTTP API template, managed with cargo-lambda and deployed with Terraform.
For a short explanation of how the three crates work together, including the trie router, see AISUMMARY.md.
lambdamuxis the user-facing facade crate.lambdamux-corecontains the generic trie-based routing primitives.lambdamux-macroprovides the#[route(...)]andgenerate_routes!()macros.
- route registration with
#[route(path = ..., method = ...)] - compile-time route table generation with
generate_routes!() - built-in API Gateway v2 dispatch with
handle_apigw_v2! - built-in API Gateway v1 dispatch with
handle_apigw_v1! - synchronous and asynchronous route handlers in the same route table
- path parameter matching such as
/hello/:id
Add these dependencies to your Lambda crate:
[dependencies]
aws_lambda_events = { version = "1.2.0", default-features = false, features = ["apigw"] }
lambda_runtime = "1.3.0"
serde_json = "1.0"
tokio = "1.52.3"
lambdamux = "1.0.3"Inside this repository, rust/test_lambda uses the local workspace crate:
lambdamux = { version = "1.0.3", path = "../lambdamux" }Create a route module such as hello.rs:
use aws_lambda_events::apigw::{ApiGatewayV2httpRequest, ApiGatewayV2httpResponse};
use aws_lambda_events::encodings::Body;
use aws_lambda_events::http::{HeaderMap, Result};
use lambda_runtime::LambdaEvent;
use lambdamux::route;
use serde_json::{json, Value};
fn json_response(status_code: i64, value: Value) -> ApiGatewayV2httpResponse {
let mut headers = HeaderMap::new();
headers.insert("content-type", "application/json".parse().unwrap());
let mut response = ApiGatewayV2httpResponse::default();
response.status_code = status_code;
response.body = Some(Body::Text(value.to_string()));
response.headers = headers.clone();
response.multi_value_headers = headers;
response
}
#[route(path = "/hello", method = "get")]
pub async fn hello_get(
_event: LambdaEvent<ApiGatewayV2httpRequest>,
) -> Result<ApiGatewayV2httpResponse> {
Ok(json_response(200, json!({ "success": true })))
}
#[route(path = "/hello/:id", method = "get")]
pub fn hello_id_get(
event: LambdaEvent<ApiGatewayV2httpRequest>,
) -> Result<ApiGatewayV2httpResponse> {
let id = event
.payload
.path_parameters
.get("id")
.cloned()
.unwrap_or_default();
Ok(json_response(200, json!({
"success": true,
"id": id,
})))
}
#[route(path = "/hello", method = "post")]
pub async fn hello_post(
event: LambdaEvent<ApiGatewayV2httpRequest>,
) -> Result<ApiGatewayV2httpResponse> {
let body = event.payload.body.unwrap_or("{}".into());
let body: Value = serde_json::from_str(&body).unwrap_or(json!({}));
let Some(name) = body.get("name").and_then(|value| value.as_str()) else {
return Ok(json_response(400, json!({
"success": true,
"name": "not found",
})));
};
Ok(json_response(201, json!({
"success": true,
"name": name,
})))
}Then wire the Lambda entry point in main.rs:
use aws_lambda_events::apigw::{ApiGatewayV2httpRequest, ApiGatewayV2httpResponse};
use aws_lambda_events::encodings::Error;
use lambda_runtime::{service_fn, LambdaEvent};
mod hello;
use hello::*;
async fn handler(
event: LambdaEvent<ApiGatewayV2httpRequest>,
) -> Result<ApiGatewayV2httpResponse, Error> {
lambdamux::handle_apigw_v2!(event)
}
#[tokio::main]
async fn main() -> Result<(), Error> {
lambda_runtime::run(service_fn(handler)).await
}That is enough to route requests like:
GET /helloGET /hello/123POST /hello
Route handlers can be synchronous or asynchronous, and both forms can be mixed in the same Lambda:
#[route(path = "/health", method = "get")]
pub fn health(
event: LambdaEvent<ApiGatewayV2httpRequest>,
) -> Result<ApiGatewayV2httpResponse> {
// Return a response directly.
}
#[route(path = "/users/:id", method = "get")]
pub async fn user(
event: LambdaEvent<ApiGatewayV2httpRequest>,
) -> Result<ApiGatewayV2httpResponse> {
// Await database, HTTP, or other asynchronous work before returning.
}No extra dispatch setup is needed. handle_apigw_v1! and handle_apigw_v2! await the selected route internally.
If your Lambda is fronted by API Gateway REST API payloads instead of HTTP API v2 payloads, use ApiGatewayProxyRequest, ApiGatewayProxyResponse, and the handle_apigw_v1! macro instead.
Before building or deploying the template, install:
- Rust from rust-lang.org
cargo-lambdafrom cargo-lambda.info- Terraform from hashicorp.com
Run the workspace tests from the Rust workspace:
cd rust
cargo test --workspaceBuild the Lambda function for the x86_64-unknown-linux-gnu target:
cargo lambda build --release --target x86_64-unknown-linux-gnuThis produces a binary in target/lambda/<function-name>. The Terraform example handles this build automatically.
To run a focused test:
cargo test --package test_lambda --bin test_lambda -- hello::hello_tests --show-output
cargo test --package test_lambda --bin test_lambda -- hello::hello_tests::hello_get_test --exact --show-outputThis repository includes a Terraform example that shows how to deploy a lambdamux Lambda behind API Gateway:
- Terraform example: https://github.com/anuradhawick/rs_template/tree/main/terraform
That example currently:
- builds the Rust Lambda from
rust/test_lambda - packages it with
cargo lambda build - creates an API Gateway HTTP API
- forwards
ANY /{proxy+}to the Lambda function
Typical usage looks like this:
cd terraform
terraform init
terraform applyIf your crate path or Lambda binary name is different, update the Terraform source_path and function settings before applying.
Follow the style in rust/test_lambda to add route modules, tests, and handlers.
To add another Lambda crate to the workspace:
cd rust
cargo new test_lambda_2Then add the dependencies from the installation section, wire a handler with handle_apigw_v2!, and add Terraform to route traffic to the new Lambda. The examples in terraform-aws-apigateway-v2 are a useful reference.
For non-HTTP Lambda events, use serde_json::Value, the relevant aws_lambda_events event type, or your own serde structs.
You can authenticate inside main.rs or a route module such as hello.rs. The event object includes the complete request context, including API Gateway authorizer context.
Useful checks before publishing or deploying:
cd rust
cargo test --workspace
cargo deny checkWhen publishing the crates manually, publish them in dependency order: lambdamux-core, lambdamux-macro, then lambdamux. The GitHub release workflow follows the same order.
- The internal route cache is managed by
lambdamux; users do not need to define a globalLazyorOnceLock. lambdamuxis the user-facing facade crate. The repository also containslambdamux-coreandlambdamux-macro, but most users only needlambdamux.
Licensed under either GPL-3.0-only or Apache-2.0, at your option.