Web frameworks
Validate API Gateway / ALB requests of lambda_http and raw lambda_runtime events with vld schemas.

Validation for lambda_http 1.x functions (API Gateway REST / HTTP APIs, ALB, Function URLs, VPC Lattice) and for raw lambda_runtime events. Requests get the same 422 / 415 responses and parameter rules as every HTTP module.

Install

Cargo.toml
[dependencies]
vld = "0.8"
vld-web = { version = "0.8", features = ["lambda"] }
lambda_http = "1"

Module vld_web::lambda. lambda_runtime is used through lambda_http's re-export (lambda_http::lambda_runtime), so there is one dependency.

Example

use lambda_http::{run, service_fn, Body, Error, Request, Response};
use vld_web::lambda::{validate_json, validate_path};

vld::schema! {
    #[derive(Debug)]
    pub struct UserPath {
        pub id: i64 => vld::number().int().min(1),
    }
}

vld::schema! {
    #[derive(Debug)]
    pub struct UpdateUser {
        pub name: String => vld::string().min(2),
    }
}

async fn handler(req: Request) -> Result<Response<Body>, Error> {
    let path: UserPath = match validate_path(&req) {
        Ok(p) => p,
        Err(resp) => return Ok(resp), // 422
    };
    let body: UpdateUser = match validate_json(&req) {
        Ok(b) => b,
        Err(resp) => return Ok(resp), // 422 / 415
    };
    Ok(Response::new(format!("{}: {}", path.id, body.name).into()))
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    run(service_fn(handler)).await
}

Raw events

use lambda_http::lambda_runtime::{Diagnostic, LambdaEvent};

async fn handler(event: LambdaEvent<serde_json::Value>) -> Result<String, Diagnostic> {
    let (order, _context) = vld_web::lambda::validate_event::<Order>(event)?;
    Ok(order.id)
}

A failed invocation reports errorType "ValidationError" and errorMessage the 422 body as JSON text.

API

FunctionPurpose
validate_json::<T>(&req)JSON body; Err(Response) 415 without a JSON Content-Type, 422 otherwise
validate_query::<T>(&req)queryStringParameters (multi-value keys become arrays)
validate_path::<T>(&req)pathParameters
error_response(&VldHttpError)The JSON error response (error_response(&err.into()) for a VldError)
validate_event::<T>(LambdaEvent<Value>)Result<(T, Context), Diagnostic>
event_error(&VldError)The Diagnostic for a failed event
preludeAll of the above plus vld::prelude::*

Gotchas

  • Query and path parameters are read from the event (RequestExt::query_string_parameters / path_parameters), which API Gateway has already decoded, then coerced like every other query / path extractor (?page=2 fills an integer, ?q=123 a string).
  • No body limit of its own: Lambda caps payloads at 6 MB.
  • lambda_http is a dependency with its default features (every event source).