Module extract

Module extract 

Source
Expand description

Request data extraction module

This module provides functionality for extracting typed data from HTTP requests. It includes extractors for common data formats and patterns:

  • Form data (Form<T>) - For application/x-www-form-urlencoded request bodies
  • JSON data (Json<T>) - For application/json request bodies
  • Query parameters (Query<T>) - For URL query strings
  • Headers and other request metadata
  • Raw request body as bytes or string

§Core Concepts

The module is built around the FromRequest trait, which defines how to extract typed data from requests. Types implementing this trait can be used as parameters in request handlers.

§Common Extractors

§Form Data

#[derive(Deserialize)]
struct LoginForm {
    username: String,
    password: String,
}

async fn handle_login(Form(form): Form<LoginForm>) {
    println!("Login attempt from: {}", form.username);
}

§JSON Data

#[derive(Deserialize)]
struct User {
    name: String,
    email: String,
}

async fn create_user(Json(user): Json<User>) {
    println!("Creating user: {}", user.name);
}

§Query Parameters

#[derive(Deserialize)]
struct Pagination {
    page: u32,
    per_page: u32,
}

async fn list_items(Query(params): Query<Pagination>) {
    println!("Listing page {} with {} items", params.page, params.per_page);
}

§Optional Extraction

All extractors can be made optional by wrapping them in Option<T>:

#[derive(Deserialize)]
struct UpdateUser {
    name: Option<String>,
    email: Option<String>,
}

async fn update_user(Json(update): Json<UpdateUser>) {
    if let Some(name) = update.name {
        println!("Updating name to: {}", name);
    }
}

§Multiple Extractors

Multiple extractors can be combined using tuples:

#[derive(Deserialize)]
struct SearchParams {
    q: String,
}

#[derive(Deserialize)]
struct Payload {
    data: String,
}

async fn handler(
    method: Method,
    Query(params): Query<SearchParams>,
    Json(payload): Json<Payload>,
) {
    // Access to method, query params, and JSON payload
}

Structs§

Form
Represented as form data
Json
Represented as JSON data
Query
Represented as url query data

Traits§

FromRequest