Extractors: Reading Client Input
6 min read
Welcome back, Rustacean! 🦀
In the previous module, we set up a basic "Hello World". That’s cute, but useless. Real applications need to listen. They need to read data sent by the user—whether it’s a JSON payload, a secret authorization token, or a messy HTML form.
In most legacy frameworks, you have a request object and you have to dig inside it like a raccoon looking for trash in a dumpster. You'd do things like req.body.get("username").unwrap().
Axum is different. Axum is elegant. Axum uses Extractors.
1. The Magic of Extractors: How Axum Parses Requests
The Definition
An Extractor is a piece of logic in Axum that looks at an incoming HTTP request, takes the part you care about, turns it into a Rust type, and hands it to your function.
The Problem
Imagine writing a server in raw TCP. You receive a stream of bytes. You have to write code to:
- Find the start of the body.
- Parse the headers.
- Check if the content type matches what you expect.
- Convert bytes to strings, then strings to objects.
- Handle errors if the user sent "banana" instead of a number.
If you had to do this manually for every endpoint, you would quit programming and become a goat farmer. 🐐
The Solution
Axum uses Rust's type system to do this automatically. You don't ask Axum for data; you just declare what you want in your function arguments.
If your handler function asks for Json<User>, Axum automatically checks the headers for application/json, reads the body, parses it, and gives you a User struct. If the format is wrong, Axum sends a 400 Bad Request before your code even runs.
How it Works (Under the Hood)
Axum relies on the FromRequest trait. When a request hits your endpoint, Axum looks at the signature of your handler function. It iterates through the arguments, calling from_request for each one.
⚠️ The Golden Rule of Extractors:
You can only have one extractor that consumes the request body (like JSON or Form data), and it must be the last argument in your function. Headers and Query parameters do not consume the body, so they can go anywhere.
2. Parsing JSON Payloads: Accepting Structured Data
The Problem
99% of modern APIs communicate via JSON. You need to turn { "username": "admin" } into a Rust struct safely.
The Solution: axum::Json
We use the Json wrapper type combined with the legendary serde crate.
Step-by-Step Implementation
1. Add Dependencies
You need serde with the derive feature to simplify struct creation.
[dependencies]
axum = "0.7"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }2. Define your DTO (Data Transfer Object)
Industry standard: Don't use your database models directly for API input. Create a specific struct for the request.
use serde::Deserialize;
// Derive Deserialize so Serde can unpack JSON into this struct
#[derive(Deserialize)]
struct CreateUserRequest {
username: String,
email: String,
age: u8,
}3. The Handler
Notice we don't return Result here just to keep it simple, but in real life, you would.
use axum::{Json, response::IntoResponse};
async fn create_user(
// Axum sees "Json<T>" and activates the JSON extractor logic
Json(payload): Json<CreateUserRequest>
) -> impl IntoResponse {
// If we reach this line, 'payload' is guaranteed to be valid.
// No .unwrap(), no parsing logic needed here!
println!("New user: {} ({})", payload.username, payload.email);
// We can also return JSON easily
Json(serde_json::json!({ "status": "User created", "id": 123 }))
}🔥 Funny Fact: If a user sends a string where the
age(u8) is expected, Axum automatically replies with a text-based error explaining exactly what field failed. It’s like having a bouncer who not only kicks people out but prints them a receipt explaining why their shoes were too ugly.
3. Form Data: Handling Traditional HTML Form Submissions
The Problem
Sometimes you aren't building a Single Page App (SPA). You are building a simple login page using standard HTML <form action="/login" method="POST">.
Browsers send this data as application/x-www-form-urlencoded, not JSON. If you try to use the JSON extractor, it will fail.
The Solution: axum::Form
Just swap Json for Form. The underlying mechanism is identical.
Implementation
use axum::Form;
use serde::Deserialize;
#[derive(Deserialize)]
struct LoginRequest {
username: String,
password: String, // In production, never log this! 🤫
}
async fn login_handler(
// The extractor logic now expects "application/x-www-form-urlencoded"
Form(input): Form<LoginRequest>
) -> impl IntoResponse {
if input.username == "admin" && input.password == "secret" {
"Welcome back, Commander."
} else {
"Who goes there?"
}
}💡 Industry Tip: Even if you love JSON, always know how to handle Forms. Webhooks from third-party services (like Stripe or Slack) often use Form encoding.
4. Reading Headers: Extracting Authorization and Custom Headers
The Problem
Metadata lives in the headers. This is where API keys, Content-Types, and User-Agents live. This data is not in the body.
The Solution: HeaderMap (or TypedHeader)
The most raw and flexible way is using HeaderMap.
Implementation: The "Manual" Way (Standard)
This is available in Axum core.
use axum::http::HeaderMap;
async fn secure_handler(headers: HeaderMap) -> String {
// Extract the "user-agent" to see if they are using curl, chrome, or a toaster
let user_agent = headers
.get("user-agent")
.and_then(|v| v.to_str().ok())
.unwrap_or("Unknown Browser");
// Check for a fake API key
if let Some(key) = headers.get("x-api-key") {
if key == "super-secret-password" {
return format!("Access Granted to {}", user_agent);
}
}
format!("Access Denied. Nice try, {}", user_agent)
}The "Pro" Way (TypedHeader)
Parsing headers manually (checking for strings, handling non-ASCII characters) is prone to bugs. axum-extra provides Typed Headers.
- Add
axum-extrawithtyped-headerfeature. - Use it to auto-extract things like Bearer tokens.
use axum_extra::headers::{Authorization, authorization::Bearer};
use axum_extra::TypedHeader;
// This function ONLY runs if a valid Bearer token is present
async fn protected_resource(
TypedHeader(auth): TypedHeader<Authorization<Bearer>>
) -> String {
// Axum has already parsed the "Authorization: Bearer <token>" string
let token = auth.token();
format!("I see your token: {}", token)
}🏗️ Putting It All Together (Boilerplate)
Here is a runnable main.rs encompassing these concepts.
use axum::{
routing::{get, post},
Router, Json, Form, http::HeaderMap
};
use serde::Deserialize;
use std::net::SocketAddr;
#[tokio::main]
async fn main() {
// 1. Build our application with routes
let app = Router::new()
.route("/", get(root))
.route("/json", post(accept_json))
.route("/form", post(accept_form))
.route("/headers", get(read_headers));
// 2. Define the address
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
println!("Listening on {}", addr);
// 3. Serve it
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn root() -> &'static str {
"Send a POST to /json, /form, or GET /headers"
}
// --- JSON ---
#[derive(Deserialize)]
struct User {
name: String,
email: String,
}
async fn accept_json(Json(user): Json<User>) -> String {
format!("JSON Received: {} is contactable at {}", user.name, user.email)
}
// --- FORM ---
#[derive(Deserialize)]
struct SearchParams {
q: String,
page: Option<u8>,
}
async fn accept_form(Form(params): Form<SearchParams>) -> String {
format!("Searching for '{}' on page {}", params.q, params.page.unwrap_or(1))
}
// --- HEADERS ---
async fn read_headers(headers: HeaderMap) -> String {
let agent = headers
.get("user-agent")
.and_then(|v| v.to_str().ok())
.unwrap_or("Unknown");
format!("Hello, visitor from: {}", agent)
}🧠 Summary
- Extractors declaratively separate parsing logic from business logic.
- Use
Json<T>for APIs. - Use
Form<T>for HTML forms. - Use
HeaderMap(orTypedHeader) for metadata/auth. - Golden Rule: Only one body extractor per handler, and it goes last!
📚 References & Further Reading
Challenge
You are given an array of product objects. Your task is to implement the processProductData function to perform a series of data transformations.
The function should perform the following operations in order:
- Filter out any products where the
inStockproperty isfalse. - For the remaining products, if a product's
categoryis 'electronics', apply a 10% discount to itsprice. The price should be updated in the object. - Group the transformed products by their
category.
Finally, return a single object where each key is a category name and the corresponding value is an array of the processed product objects belonging to that category.
Expected result
The function should return an object with keys representing the categories of the in-stock products. The values should be arrays of the corresponding product objects, with the prices for 'electronics' discounted by 10%.
{
"electronics": [
{ "id": 1, "name": "Laptop", "category": "electronics", "price": 1080, "inStock": true },
{ "id": 5, "name": "Smartphone", "category": "electronics", "price": 720, "inStock": true },
{ "id": 7, "name": "Keyboard", "category": "electronics", "price": 81, "inStock": true }
],
"apparel": [
{ "id": 2, "name": "T-shirt", "category": "apparel", "price": 25, "inStock": true },
{ "id": 4, "name": "Jeans", "category": "apparel", "price": 75, "inStock": true },
{ "id": 8, "name": "Jacket", "category": "apparel", "price": 150, "inStock": true }
]
}