FromRequest
Learn how the FromRequest trait works in Axum, how to implement custom extractors, and how handler arguments get their values from incoming requests.
Handlers in Axum are just functions. But how do they get data from the request? If a client sends a JSON body, a header, or a query string, how does that information reach your function? The answer is a Rust trait called FromRequest. This page explains what that trait is, why Axum uses it, and how you can implement it for your own types.
What Extractors Are
An extractor is a type that Axum can create from an incoming HTTP request. When you write a handler like this:
async fn greet(body: String) -> String {
format!("You sent: {}", body)
}
The String parameter is an extractor. Axum sees that your handler wants a String, and it looks for an implementation of FromRequest for String. When the request arrives, Axum calls that implementation, gets a String back, and passes it to your handler.
You can think of extractors as a bridge between the raw HTTP request and the typed, safe values your handler wants to use. Instead of manually reading headers, parsing JSON, or extracting query parameters inside every handler, you write a type that describes the data you need, implement FromRequest once, and then use that type directly as a handler argument.
Built-in extractors like String, Bytes, Json<T>, Query<T>, and HeaderMap all implement FromRequest. But you can also implement it for your own custom types. That is the main focus of this page.
The FromRequest Trait
The FromRequest trait is defined roughly like this:
pub trait FromRequest<S>: Sized {
type Rejection: IntoResponse;
fn from_request(req: Request, state: &S) -> impl Future<Output = Result<Self, Self::Rejection>> + Send;
}
The trait method returns a future rather than being written as async fn in the trait itself. When you implement the trait you write an ordinary async fn from_request, which satisfies that signature. Rust has supported async fn in traits since Rust 1.75, so no extra crate is needed.
Let's break that down piece by piece.
Sis a generic parameter representing the application state. Most apps use()if they don't have shared state, or a custom struct if they do.Sizedmeans the type that implements this trait must have a known size at compile time, which almost all structs and enums do.type Rejectionis an associated type. When extraction fails - for example, the request body is missing a required field - you return this type instead ofSelf. The rejection must implementIntoResponse, because Axum will send it back to the client as an error response.- The
from_requestfunction receives the entireRequestobject, which includes all headers, the method, the URI, and the body. It also receives a reference to the application state. It must return either a successfully extracted value (Ok(Self)) or a rejection (Err(Self::Rejection)).
This is the whole contract. Implement it correctly, and your type becomes an extractor.
What S is when you have no state:
The S in FromRequest<S> is the type of your application state, the value you pass to .with_state(...). If your app has no shared state, S is (), the empty tuple type, and you can ignore the state argument entirely. The generic impl<S> ... where S: Send + Sync used in the examples below works for any state type, including ().
The Request type used here is axum::extract::Request, a type alias for http::Request<axum::body::Body>: an http crate request whose body type is Axum's Body. It is generic over the body type, but in practice Axum uses axum::body::Body. You don't need to worry about that detail for now.
How Axum Calls FromRequest
When you define a route with a handler that has parameters, Axum inspects the function signature at compile time. For each parameter, it finds the matching implementation of FromRequest. When a request arrives, Axum calls from_request for each parameter in the order they appear in the function signature.
The order matters because from_request can consume the request body. A handler can have at most one body-consuming extractor, and it must be the last parameter: Axum's Handler implementation requires every earlier parameter to implement FromRequestParts, so a second body extractor, or a body extractor placed before another parameter, fails to compile. There is no runtime case where one extractor eats the body and a later one finds it gone.
For now, understand that Axum handles the mechanical work: it parses the request, calls your extractor, and passes the value to your function. Your job is only to write the type and its implementation.
A First Custom Extractor
Let's create a simple extractor that reads a custom header from the request. Suppose clients always send a header called x-user-id. You want your handlers to receive a UserId value instead of a raw HeaderValue.
Start with a newtype wrapper around a String:
#[derive(Debug)]
struct UserId(String);
Now implement FromRequest for this type:
use axum::{
extract::{FromRequest, Request},
http::StatusCode,
};
impl<S> FromRequest<S> for UserId
where
S: Send + Sync,
{
type Rejection = (StatusCode, &'static str);
async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> {
let header_value = req
.headers()
.get("x-user-id")
.and_then(|value| value.to_str().ok())
.ok_or((StatusCode::BAD_REQUEST, "missing x-user-id header"))?;
Ok(UserId(header_value.to_string()))
}
}
There are several things to notice here.
First, the implementation is generic over S with a bound S: Send + Sync. Most Axum implementations use this bound because the state must be safe to share across tasks. If you don't need the state, you can ignore it with _state.
Second, the rejection type is a tuple (StatusCode, &'static str). This tuple already implements IntoResponse, so we don't need to write our own type. Many simple extractors can use this trick.
Third, inside from_request we call req.headers().get("x-user-id"). This returns an Option<&HeaderValue>. We convert the header value to a string with to_str(), which also returns an Option because headers are bytes and may contain invalid UTF-8. If any of these steps fail, we return an error tuple with a status code and a message.
Finally, if everything succeeds, we return Ok(UserId(...)).
Now you can use this extractor in a handler:
async fn get_user_id(user_id: UserId) -> String {
format!("User ID is: {:?}", user_id)
}
And attach it to a router:
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/user-id", get(get_user_id));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
If you run this app and send a request with the header x-user-id: 123, you'll get the string User ID is: UserId("123"). If you omit the header, you'll get a 400 Bad Request with the message missing x-user-id header.
Works as expected:
If you see that output, your first custom extractor is working correctly. You've implemented FromRequest and used it in a handler.
A Body-Consuming Extractor
Reading a header is useful, but FromRequest really shines when you need to access the request body. Let's build an extractor that reads the entire body as a String and then validates that it is not empty.
Define a type:
struct NonEmptyBody(String);
Implement FromRequest:
use axum::{
extract::{FromRequest, Request},
http::StatusCode,
};
impl<S> FromRequest<S> for NonEmptyBody
where
S: Send + Sync,
{
type Rejection = (StatusCode, &'static str);
async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> {
let body_bytes = axum::body::to_bytes(req.into_body(), usize::MAX)
.await
.map_err(|_| (StatusCode::BAD_REQUEST, "failed to read body"))?;
let body_string = String::from_utf8(body_bytes.to_vec())
.map_err(|_| (StatusCode::BAD_REQUEST, "body was not valid UTF-8"))?;
if body_string.trim().is_empty() {
return Err((StatusCode::BAD_REQUEST, "body cannot be empty"));
}
Ok(NonEmptyBody(body_string))
}
}
This implementation consumes the request body by calling req.into_body(), which moves the body out of the request. We then read all the bytes with axum::body::to_bytes. The second argument, usize::MAX, is a body size limit. If the body is larger than that limit, the function returns an error. We'll talk more about limits later.
After reading the bytes, we convert them to a UTF-8 string. If the bytes are not valid UTF-8, we reject. Finally, we check that the trimmed string is not empty.
Now use this extractor in a handler that echoes the body back:
async fn echo_non_empty(body: NonEmptyBody) -> String {
format!("You sent: {}", body.0)
}
Attach it to a POST route:
use axum::{routing::post, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/echo", post(echo_non_empty));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Send a POST request with a non-empty body, and the handler returns it back. Send an empty body or a body that isn't UTF-8, and you'll get an error.
Body-consuming extractors must be last:
This extractor consumes the body. A handler with a body-consuming extractor in any position except the last does not compile, because Axum requires every earlier parameter to implement FromRequestParts. Always place body-consuming extractors as the last argument in your handler function.
Using a Custom Rejection Type
Using (StatusCode, &'static str) for rejections is fine for quick examples, but real applications often want structured error responses. You can define your own rejection type as long as it implements IntoResponse.
Let's create a rejection type with a status code and a message that can change at runtime:
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
#[derive(Debug)]
struct ApiError {
status: StatusCode,
message: String,
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
(self.status, self.message).into_response()
}
}
Now modify the NonEmptyBody extractor to use ApiError:
impl<S> FromRequest<S> for NonEmptyBody
where
S: Send + Sync,
{
type Rejection = ApiError;
async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> {
let body_bytes = axum::body::to_bytes(req.into_body(), usize::MAX)
.await
.map_err(|_| ApiError {
status: StatusCode::BAD_REQUEST,
message: "failed to read body".to_string(),
})?;
let body_string = String::from_utf8(body_bytes.to_vec())
.map_err(|_| ApiError {
status: StatusCode::BAD_REQUEST,
message: "body was not valid UTF-8".to_string(),
})?;
if body_string.trim().is_empty() {
return Err(ApiError {
status: StatusCode::BAD_REQUEST,
message: "body cannot be empty".to_string(),
});
}
Ok(NonEmptyBody(body_string))
}
}
Now your rejection carries a dynamic message and a status code. The client receives a response with that status and the message as the body. This pattern is common in production APIs.
Implementing FromRequest Step by Step
Building a custom extractor follows a consistent process. Here is a Stepper that breaks down the steps using the header example we already saw:
Step 1: Define the type
Create a struct or enum that will hold the extracted data.
struct UserId(String);
Step 2: Implement the FromRequest trait
Write the impl block with the from_request function. Decide what rejection type to use.
impl<S> FromRequest<S> for UserId
where
S: Send + Sync,
{
type Rejection = (StatusCode, &'static str);
async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> {
// extraction logic here
}
}
Step 3: Write the extraction logic
Access the request parts or body, validate, and return Ok or Err.
let value = req.headers()
.get("x-user-id")
.and_then(|v| v.to_str().ok())
.ok_or((StatusCode::BAD_REQUEST, "missing header"))?;
Ok(UserId(value.to_string()))
Step 4: Use the extractor in a handler
Add the type as a parameter in any handler function.
async fn handler(user_id: UserId) -> String {
format!("{:?}", user_id)
}
Multiple Ways to Extract Data
There is often more than one way to implement an extractor for the same logical data. Consider a case where you want to extract a numeric ID from a header. You could use String and then parse it yourself, or you could use a typed approach.
Option 1: Parse inside from_request
struct NumericId(u32);
impl<S> FromRequest<S> for NumericId
where
S: Send + Sync,
{
type Rejection = (StatusCode, &'static str);
async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> {
let raw = req.headers()
.get("x-numeric-id")
.and_then(|v| v.to_str().ok())
.ok_or((StatusCode::BAD_REQUEST, "missing header"))?;
let parsed = raw.parse::<u32>()
.map_err(|_| (StatusCode::BAD_REQUEST, "invalid number"))?;
Ok(NumericId(parsed))
}
}
Option 2: Return the raw string and parse in the handler
use axum::{
extract::{FromRequest, Request},
http::StatusCode,
};
struct RawId(String);
impl<S> FromRequest<S> for RawId
where
S: Send + Sync,
{
type Rejection = (StatusCode, &'static str);
async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> {
let raw = req
.headers()
.get("x-numeric-id")
.and_then(|v| v.to_str().ok())
.ok_or((StatusCode::BAD_REQUEST, "missing header"))?;
Ok(RawId(raw.to_string()))
}
}
async fn handler(raw: RawId) -> Result<String, String> {
let num = raw.0.parse::<u32>().map_err(|_| "invalid number".to_string())?;
Ok(format!("Number is {}", num))
}
The extractor only reads the header and hands the raw string to the handler, which parses it and returns its own error message when the value is not a number. The handler returns Result<String, String> here because String implements IntoResponse for both the success and the error case, but that has a catch: Axum turns the Err into a plain 200 response carrying the message as its body, which looks like success to the client. In a real application you would return a typed error with the status you want, such as (StatusCode, String), instead of a bare String.
Both approaches work. The first moves the parsing into the extractor, keeping the handler clean. The second gives the handler more control over error handling. Choose based on how much logic belongs at the boundary versus inside the business logic.
Common Mistakes and Misconceptions
Implementing FromRequest looks simple, but there are several pitfalls that beginners often hit.
Consuming the body too early
If you call req.into_body() inside your from_request, the body is gone for any other extractor that comes after yours. That ordering is not something you discover at runtime: a handler with a body-consuming extractor anywhere except the last position fails to compile, because every earlier parameter must implement FromRequestParts. Always place body-consuming extractors last. If you need to access parts and body together, use FromRequestParts for the parts, but that's outside this page's scope.
Forgetting to implement IntoResponse for the rejection
If your rejection type doesn't implement IntoResponse, the compiler will complain. The simplest solution is to use a tuple like (StatusCode, &'static str) or a custom struct that derives nothing but manually implements IntoResponse.
Not handling all error cases
to_str() returns Option, parse::<u32>() returns Result, and to_bytes returns a Result. You must map every possible failure to a rejection. Calling unwrap on a Result that turns out to be Err panics the handler task. Axum has no default panic catcher, so the client gets no response at all (the connection is closed without a reply) and only that request fails; the server itself keeps running. That is rarely what you want, so map the failure to a rejection instead.
Confusing FromRequest with FromRequestParts
FromRequest gives you the entire request, including the body. FromRequestParts only gives you the request head (method, URI, headers) without the body. If you only need headers or the URI, consider using FromRequestParts because it is more efficient and doesn't force you to consume the body.
Assuming the body is always valid UTF-8
Bodies are raw bytes. If you want a string, you must convert with String::from_utf8 and handle the error case. Many clients send binary data or encoded content.
Body limit is important:
The to_bytes function accepts a limit. We used usize::MAX, which effectively removes the limit. In production, you should set a reasonable limit to prevent a client from sending an enormous body and exhausting memory. Built-in body extractors such as Json, String, and Bytes apply a 2 MB default limit on their own, but a custom extractor is responsible for its own limit, so the usize::MAX above is only safe for a demo.
Summary
The FromRequest trait is the foundation of Axum's extractor system. It lets you turn a raw HTTP request into typed, validated data that your handlers can use safely. By implementing this trait for your own types, you centralize request parsing and error handling, keeping your handlers focused on business logic.
The key insight is that FromRequest gives you complete access to the request - headers, method, URI, and body. You decide how to interpret that data and what to return when interpretation fails. Once you understand this trait, you can build extractors for any data shape your application needs, from simple header readers to complex multi-field validators.
If you've written a custom extractor that reads the body and returns a custom rejection type, you have everything you need to start extracting request data in a clean, maintainable way. The next natural step is to learn how to extract only the request head without consuming the body, which unlocks even more flexible handler signatures.