tezvyn:

The FromRequest Trait: Consuming Request Bodies in Axum

AI-drafted, machine-checkedSource: docs.rsadvanced

Axum's `FromRequest` trait defines how to create a type by consuming an HTTP request body. It's the core of extractors like `Json<T>` that deserialize POST data. The footgun: you can only use one `FromRequest` extractor per handler, as it consumes the body.

WHY IT EXISTS: Web frameworks need a standardized, extensible way to transform raw HTTP requests into structured, typed data for handler functions. The FromRequest trait provides this pattern for operations that require reading and consuming the request body.

THE MENTAL MODEL: Think of FromRequest as a contract that says, "I know how to build myself from an incoming request, and I will consume the request body to do it." By implementing this trait for a type, you teach Axum how to provide it as an argument to a handler function, abstracting away the boilerplate of request parsing.

HOW IT WORKS: A type implementing FromRequest must define an async method, from_request. This function receives the request and application state. It attempts to extract and convert the body, returning Ok(Self) on success or an Err(Rejection) on failure. The Rejection associated type must be convertible into an HTTP response, allowing extractors to fail gracefully with codes like 400 Bad Request.

WHEN TO USE IT: Use FromRequest when your extractor needs to read the request body. This is essential for deserializing a JSON or form-urlencoded body into a struct (e.g., Json<User>), reading the raw request body into Bytes or a String, or handling multipart form data.

WHEN NOT TO USE IT: Do not use FromRequest if your extractor only needs metadata and not the body. For extracting path parameters (Path<T>), query strings (Query<T>), or headers (TypedHeader<T>), you must use the FromRequestParts trait instead. This is a critical distinction, as multiple FromRequestParts extractors can be used, but only one FromRequest extractor is allowed because it consumes the body.

ONE CANONICAL EXAMPLE: A common Axum handler is async fn create_user(Json(payload): Json<User>). Here, Json<User> is an extractor that implements FromRequest. Axum sees this argument, calls Json::<User>::from_request, which reads the body, deserializes it into a User struct, and provides the result to the handler. If deserialization fails, it automatically returns a 400 Bad Request response.

Read the original → docs.rs

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.