Extractors
An extractor is a typed argument to a handler that is built from the request: path params, query strings, JSON bodies, headers, and shared state.
Detailed Explanation
Instead of fn handler(req: Request) and a pile of string lookups, Axum (and Actix) let you write async fn handler(Path(id): Path<u64>, Json(body): Json<Update>). Each argument implements a trait that knows how to consume or borrow parts of the request. If extraction fails — a path that is not a u64, a body that is not JSON — the framework returns an error response and your function does not run.
Order matters in Axum. Extractors that consume the body (Json, Form, RawBody) can appear once. Extractors that read parts (Path, Query, HeaderMap, State) can appear together. The compiler error when you take two body consumers is the reminder. Put State first by convention so the signature reads like dependencies then input.
Custom extractors are how you do auth. struct CurrentUser(User); plus FromRequestParts that reads a cookie, hits the session store, and returns Err(401) or the user. Every handler that needs a user takes CurrentUser and never sees the cookie logic. That is cleaner than a middleware that stuffs an extension map with a stringly-typed value.
Rejection types are part of your API. A default Json rejection is a 422 or 400 with a framework-shaped body. You can replace it so the error JSON matches the rest of your app.
When you write an extractor: repeated request parsing, auth, tenancy. When you read Request yourself: a rare streaming body. When you put everything in State: you are smuggling request data through a global — stop.
Write a unit test for a custom extractor with Request::builder and from_request_parts. You do not need to bind a port to prove that a missing cookie is 401. Handler tests can then assume CurrentUser is already valid and focus on the business branch.
Code Examples
struct PathId(u64);
fn parse_id(raw: &str) -> Result<PathId, &'static str> {
raw.parse().map(PathId).map_err(|_| "not a u64")
}
fn main() {
let id = parse_id("17").unwrap();
println!("{}", id.0); // prints: 17
}Common Gotchas
Only one extractor can consume the body
`Json` plus `String` body in one handler will not compile. Clone the bytes first, or pick one.
Failed extraction skips the handler
Your logs inside the handler will not run. Log at a layer, or customise the rejection.
Auth as an extractor beats a hidden extension
The handler signature lists `CurrentUser`. That is documentation the compiler enforces.
Do not take `String` for a JSON body if you have a struct
You skip validation. Extract `Json<T>`.