Implementing Custom Extractors with FromRequestParts
Learn how to build your own Axum extractors that only need request metadata like headers and extensions using the FromRequestParts trait, with step-by-step examples and best practices.
When you need to read something from an incoming request - a header, a query parameter, a value from shared state - you use an extractor. Axum provides many built-in extractors, but sometimes you need to build your own. This page teaches you how to implement a custom extractor using the FromRequestParts trait, which is the right tool when your extractor only needs the request's metadata and not its body.
Why FromRequestParts Exists
Think of an incoming HTTP request as two separate bundles of information. The first bundle is the parts: the method, URI, headers, HTTP version, and any extensions you have attached to the request. The second bundle is the body: the raw bytes of content that the client sends, such as a JSON payload or form data.
Axum has two traits for building extractors that match these bundles. FromRequest gives you access to both the parts and the body, which means you can read the request's content. FromRequestParts gives you access only to the parts. It cannot read the body.
This separation matters for two reasons. First, extracting only parts is cheaper because the body stays untouched, so your handler or middleware can still read it later if needed. Second, extractors that only need parts can run before any body-consuming extractor in the same handler. Axum enforces an order: body-consuming extractors must come last. If your extractor doesn't need the body, it can be placed anywhere in the argument list, which makes handler signatures more flexible.
Imagine you are building an API where every request must carry an X-Tenant-ID header to identify which organization the user belongs to. Your extractor reads that header and converts it into a Tenant struct. It never looks at the body. Using FromRequestParts for this is the perfect fit - you don't accidentally consume the body, and the extractor runs early, so any error can be handled before the body is touched.
FromRequest vs FromRequestParts:
FromRequest is the more general trait; FromRequestParts is a specialized version. If you only need parts, always implement FromRequestParts. It is more efficient and composes better with other extractors. Only implement FromRequest when you truly need to read the request body.
The Trait in Plain Language
The FromRequestParts trait has one method you must implement:
fn from_request_parts(
parts: &mut http::request::Parts,
state: &S
) -> impl Future<Output = Result<Self, Self::Rejection>> + Send;
The trait method returns a future. In your implementation you write it as an ordinary async fn from_request_parts, which satisfies that signature, and you need no extra crate to do so.
You get a mutable reference to the request's parts and a shared reference to the application state (if any). You return either your extractor type (Ok(Self)) or an error (Err(Self::Rejection)). The rejection type must implement IntoResponse, meaning it can be turned into an HTTP response to send back to the client.
The trait also has an associated type Rejection. That's the type you use when the extraction fails - for example, when a required header is missing or has an invalid value.
Implementing FromRequestParts is just writing a function that reads something from parts and either succeeds or fails. The rest of Axum handles calling your function and converting the rejection into a response when needed.
Setting Up Your Project
Let's start with a minimal Axum project so we have a foundation for all the examples. Create a new Rust project and add axum and tokio to your Cargo.toml. The serde_json line is for the custom JSON rejection example further down the page; you can leave it out until you reach that section.
[package]
name = "from_request_parts_demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde_json = "1"
No extra crate is needed:
Axum 0.8 defines its extractor traits with return-position impl Future, so you write an ordinary async fn in the implementation. Rust has supported async fn in traits since Rust 1.75, and Axum's minimum supported Rust version is 1.80. Do not add the async-trait crate: its #[async_trait] macro rewrites the method into a boxed future, which does not match Axum's trait signature and fails to compile.
Here is the basic server skeleton we'll use throughout this page:
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await.unwrap();
}
async fn handler() -> &'static str {
"Hello, world!"
}
Run the server with cargo run. You should see "listening on 127.0.0.1:3000". You can test it with curl http://127.0.0.1:3000. Now we can start building extractors.
Your First Custom Extractor: Reading a Header
We'll create an extractor that reads the X-User-Id header and stores it as a struct. If the header is missing or not a valid integer, it returns an error response.
We'll break this into a step-by-step process because the order matters: you define the type, implement the trait, then use it in a handler.
Step 1: Define the extractor type
We'll define a UserId struct that holds a u64. This struct will be the output of our extractor.
#[derive(Debug, Clone, Copy)]
struct UserId(u64);
This is a newtype wrapper around u64. Newtypes are a common Rust pattern to give a primitive a distinct type, so the compiler can prevent mixing it up with other numeric types.
Step 2: Import required types
At the top of main.rs, import the needed items:
use axum::{
extract::FromRequestParts,
http::{request::Parts, StatusCode},
response::{IntoResponse, Response},
};
Parts is the type of the parts argument we receive. StatusCode and IntoResponse are used for the rejection.
Step 3: Implement FromRequestParts
Now implement the trait. Provide the Rejection type and the from_request_parts method.
impl<S> FromRequestParts<S> for UserId
where
S: Send + Sync,
{
type Rejection = (StatusCode, &'static str);
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let header_value = parts
.headers
.get("x-user-id")
.ok_or((StatusCode::BAD_REQUEST, "missing x-user-id header"))?;
let parsed = header_value
.to_str()
.map_err(|_| (StatusCode::BAD_REQUEST, "x-user-id header is not valid UTF-8"))?
.parse::<u64>()
.map_err(|_| (StatusCode::BAD_REQUEST, "x-user-id must be a number"))?;
Ok(UserId(parsed))
}
}
The S type parameter stands for the application state type. For now we don't use state, so we ignore it. The where S: Send + Sync bound is required because the future returned by the method must be Send; Axum runs handlers on a multithreaded runtime.
Inside the method, we do three things: get the header, convert it to a string slice, and parse it as a u64. Each failure returns a tuple of (StatusCode, &'static str), which implements IntoResponse out of the box.
Step 4: Use the extractor in a handler
Change the handler to accept UserId as an argument. Axum will automatically call our from_request_parts implementation before entering the handler.
async fn handler(UserId(user_id): UserId) -> String {
format!("Your user id is {}", user_id)
}
We use pattern matching in the function parameters to destructure the UserId tuple and get the inner u64.
Step 5: Test the endpoint
Start the server and make requests with curl:
curl -H "x-user-id: 42" http://127.0.0.1:3000
You should see Your user id is 42.
Try without the header:
curl http://127.0.0.1:3000
You'll get a 400 Bad Request with the body missing x-user-id header.
Your First Custom Extractor Works:
If you saw the correct output for a valid header and the 400 error for a missing one, you have successfully implemented FromRequestParts. This is the foundation for all part-only custom extractors.
Returning a Custom Rejection Type
The tuple (StatusCode, &'static str) works fine for simple errors, but real applications often need to return structured error messages, log the failure, or include additional headers. For that, you should define a custom error type that implements IntoResponse.
Let's create a UserIdRejection enum that holds different error variants and implements IntoResponse with a JSON response.
use axum::{http::StatusCode, response::{IntoResponse, Response}, Json};
use serde_json::json;
#[derive(Debug)]
enum UserIdRejection {
MissingHeader,
InvalidUtf8,
InvalidNumber,
}
impl IntoResponse for UserIdRejection {
fn into_response(self) -> Response {
let (status, message) = match self {
UserIdRejection::MissingHeader => (StatusCode::BAD_REQUEST, "missing x-user-id header"),
UserIdRejection::InvalidUtf8 => (StatusCode::BAD_REQUEST, "x-user-id header is not valid UTF-8"),
UserIdRejection::InvalidNumber => (StatusCode::BAD_REQUEST, "x-user-id must be a number"),
};
(status, Json(json!({ "error": message }))).into_response()
}
}
Now update the implementation to use this rejection type:
impl<S> FromRequestParts<S> for UserId
where
S: Send + Sync,
{
type Rejection = UserIdRejection;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let header_value = parts
.headers
.get("x-user-id")
.ok_or(UserIdRejection::MissingHeader)?;
let parsed = header_value
.to_str()
.map_err(|_| UserIdRejection::InvalidUtf8)?
.parse::<u64>()
.map_err(|_| UserIdRejection::InvalidNumber)?;
Ok(UserId(parsed))
}
}
This gives you full control over the error response. You could also include a Display implementation for logging.
Rejection Type Must Implement IntoResponse:
If you forget to implement IntoResponse for your rejection type, the compiler will produce a long, confusing error. Always ensure your Rejection type can be turned into a response. The trait bound is part of the contract.
Accessing State in Your Extractor
The second argument to from_request_parts is &S, the application state. This lets your extractor use shared configuration, database pools, or other data.
Here's an example where an extractor checks if the user is allowed to access the system by reading a list of allowed user IDs from state.
First, define the state struct:
#[derive(Clone)]
struct AppState {
allowed_users: Vec<u64>,
}
Build the router with this state:
let state = AppState {
allowed_users: vec![1, 2, 3],
};
let app = Router::new()
.route("/", get(handler))
.with_state(state);
Now modify the extractor to use state. We'll change the UserId extractor to also verify that the user is allowed.
struct AllowedUser(u64);
impl FromRequestParts<AppState> for AllowedUser {
type Rejection = (StatusCode, &'static str);
async fn from_request_parts(
parts: &mut Parts,
state: &AppState,
) -> Result<Self, Self::Rejection> {
let user_id = parts
.headers
.get("x-user-id")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
.ok_or((StatusCode::BAD_REQUEST, "invalid x-user-id header"))?;
if !state.allowed_users.contains(&user_id) {
return Err((StatusCode::FORBIDDEN, "user not allowed"));
}
Ok(AllowedUser(user_id))
}
}
Notice the impl FromRequestParts<AppState> part - the state type is now concrete, not generic. When you use .with_state(state), Axum sets the state type for the whole router, and extractors must match it.
The handler can then use AllowedUser:
async fn handler(AllowedUser(user_id): AllowedUser) -> String {
format!("Welcome, user {}", user_id)
}
Test with curl -H "x-user-id: 1" http://127.0.0.1:3000 to see Welcome, user 1. Try with 4 and you'll get a 403 Forbidden.
Accessing Extensions from Parts
The Parts struct also contains extensions, a type-safe storage for arbitrary data inserted by middleware or other extractors. A common pattern is to have middleware authenticate a user, store the user object in extensions, and then have a custom extractor pull it out.
We'll simulate this with a simple middleware that inserts a String into extensions, then a custom extractor that reads it.
First, import Extension and middleware types:
use axum::{
extract::FromRequestParts,
http::{request::Parts, StatusCode},
middleware::{self, Next},
response::{IntoResponse, Response},
routing::get,
Extension, Router,
};
Define the extension value type and a custom extractor:
#[derive(Clone)]
struct CurrentUser(String);
struct CurrentUserExtractor(String);
impl<S> FromRequestParts<S> for CurrentUserExtractor
where
S: Send + Sync,
{
type Rejection = (StatusCode, &'static str);
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let user = parts
.extensions
.get::<CurrentUser>()
.cloned()
.ok_or((StatusCode::UNAUTHORIZED, "user not authenticated"))?;
Ok(CurrentUserExtractor(user.0))
}
}
Now the middleware that inserts the value:
async fn auth_middleware(mut request: axum::http::Request<axum::body::Body>, next: Next) -> Response {
request
.extensions_mut()
.insert(CurrentUser("alice".to_string()));
next.run(request).await
}
Wire everything together:
let app = Router::new()
.route("/", get(handler))
.layer(middleware::from_fn(auth_middleware));
The handler:
async fn handler(CurrentUserExtractor(username): CurrentUserExtractor) -> String {
format!("Hello, {}", username)
}
Now every request goes through the middleware, which inserts the user, and the extractor picks it up. If the middleware is not applied, the extractor will return a 401 Unauthorized.
This pattern is very common for authentication. It separates the authentication logic (middleware) from the authorization check (extractor), keeping handlers clean.
Extensions Are Typed and Request-Scoped:
Each request gets its own extensions map. Values are stored by their type. When you call parts.extensions.get::<CurrentUser>(), Rust knows exactly which type to look for. This avoids stringly-typed keys and gives compile-time safety.
Making Extraction Optional
Sometimes a header is optional, and you want to continue processing if it's absent. Instead of returning an error, you can make your extractor's output type Option<T>.
That only works when T implements a second trait, OptionalFromRequestParts. Axum does not wrap every extractor in Option automatically: a plain FromRequestParts extractor has no Option support, and Option<UserId> will not compile until you add the optional implementation. The optional trait has one method, from_request_parts, which returns Result<Option<Self>, Self::Rejection> instead of Result<Self, Self::Rejection>. You return Ok(None) when the value is absent and Err when it is present but invalid.
For our UserId extractor, the header is absent when there is no x-user-id header at all, and invalid when the header is present but not a number:
use axum::extract::OptionalFromRequestParts;
impl<S> OptionalFromRequestParts<S> for UserId
where
S: Send + Sync,
{
type Rejection = (StatusCode, &'static str);
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Option<Self>, Self::Rejection> {
if !parts.headers.contains_key("x-user-id") {
return Ok(None);
}
<UserId as FromRequestParts<S>>::from_request_parts(parts, state)
.await
.map(Some)
}
}
The implementation checks first whether the header exists. If it does not, it returns Ok(None) without ever running the strict extraction. If the header is present, it delegates to the ordinary FromRequestParts implementation, which rejects a non-numeric value. Now Option<UserId> works as a handler argument:
async fn optional_handler(user_id: Option<UserId>) -> String {
match user_id {
Some(UserId(id)) => format!("User id provided: {}", id),
None => "No user id provided".to_string(),
}
}
A request with no x-user-id header gives None and the handler replies No user id provided. A request with x-user-id: abc still rejects with a 400 Bad Request, because the value is present but invalid. Only genuine absence becomes None.
Be Careful What Failure Means:
When you use Option<T>, only absence becomes None. A value that is present but invalid still rejects the request, because that is what the OptionalFromRequestParts implementation decides. If you need to distinguish between "not present" and "present but wrong" in the handler itself, use Result<T, T::Rejection> as the argument instead.
Combining Multiple Parts in One Extractor
A single extractor can read several parts and combine them into one type. For example, you might want to read both the X-Request-Id header and the Authorization header, verify one, and produce a RequestContext.
Define the output type:
struct RequestContext {
request_id: String,
token: String,
}
Implement FromRequestParts that reads both headers:
impl<S> FromRequestParts<S> for RequestContext
where
S: Send + Sync,
{
type Rejection = (StatusCode, &'static str);
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let request_id = parts
.headers
.get("x-request-id")
.and_then(|v| v.to_str().ok())
.ok_or((StatusCode::BAD_REQUEST, "missing x-request-id header"))?
.to_string();
let token = parts
.headers
.get("authorization")
.and_then(|v| v.to_str().ok())
.ok_or((StatusCode::UNAUTHORIZED, "missing authorization header"))?
.to_string();
Ok(RequestContext { request_id, token })
}
}
Handler:
async fn context_handler(ctx: RequestContext) -> String {
format!("Request id: {}, token length: {}", ctx.request_id, ctx.token.len())
}
This keeps related metadata bundled together, so your handler receives one clean object instead of many parameters.
Using FromRequestParts in Middleware
While not the main focus of this page, it's worth noting that FromRequestParts is also usable inside middleware, because middleware receives the whole request and can split it into parts and body. Implementing FromRequestParts does not automatically make your extractor run in middleware; you call it yourself. Axum also ships a shortcut for exactly this, the RequestExt::extract_parts method, which runs a stateless FromRequestParts extractor against the request head while keeping the request usable afterwards. The manual version below shows what that shortcut does.
If you need to perform extraction before the handler, you can call your extractor manually inside a middleware function:
use axum::{
extract::FromRequestParts,
http::request::Parts,
middleware::Next,
response::{IntoResponse, Response},
};
async fn my_middleware(request: axum::extract::Request, next: Next) -> Response {
let (mut parts, body) = request.into_parts();
match UserId::from_request_parts(&mut parts, &()).await {
Ok(UserId(user_id)) => {
// Do something with user_id
}
Err(rejection) => {
return rejection.into_response();
}
}
let request = axum::extract::Request::from_parts(parts, body);
next.run(request).await
}
This is a more advanced pattern, but it shows that your extractor can be reused in different contexts.
Comparing FromRequestParts and FromRequest
You might wonder when to use FromRequest instead of FromRequestParts. The decision is simple: if you need to read the request body, you must use FromRequest. If you only need parts, use FromRequestParts.
Here's a side-by-side mental model:
FromRequestParts= reads metadata (headers, URI, method, extensions). Body remains untouched.FromRequest= reads metadata and body. The body is consumed (or parts of it) and cannot be used again.
Because FromRequestParts doesn't consume the body, it can be composed with body-consuming extractors in the same handler. For example:
async fn handler(
user_id: UserId, // FromRequestParts
body: String, // FromRequest (consumes body)
) -> String {
// body is still available
format!("User {} sent: {}", user_id.0, body)
}
If UserId had implemented FromRequest and consumed the body, this handler would fail to compile: Axum's Handler implementation requires every parameter except the last to implement FromRequestParts, and only the last parameter may implement FromRequest. The compiler reports that the Handler trait is not implemented for the function. By using FromRequestParts, we avoid that problem.
Never Try to Access Body in FromRequestParts:
Inside from_request_parts, you only have &mut Parts. There is no way to read the request body there. If you try to call parts.body() or similar, the code won't compile. If you think you need the body, your extractor should implement FromRequest instead.
Common Mistakes and How to Avoid Them
Several pitfalls trip up beginners when implementing FromRequestParts.
Forgetting the Send + Sync bound on S. The future returned from from_request_parts must be Send because Axum executes handlers on a multithreaded Tokio runtime. If you don't add where S: Send + Sync, the compiler will complain that the future is not Send. Add this bound to every implementation unless you have a very specific reason not to.
Returning the wrong rejection type. Your Rejection associated type must implement IntoResponse. If you accidentally set it to () or some other type that doesn't implement IntoResponse, the compiler will reject your implementation. Always double-check.
Using Parts immutably when you need mutable access for extensions. The from_request_parts method gives you &mut Parts, which is necessary if you want to insert or modify extensions. Use &mut Parts to your advantage; don't clone the parts if you can avoid it.
Not handling non-UTF8 header values. HTTP headers are bytes, not strings. HeaderValue has no as_str() method; always use .to_str(), which returns a Result that fails on invalid UTF-8, or use as_bytes() if you only need the raw bytes.
Expecting Option<T> to work for every FromRequestParts extractor. Option<T> only works when T implements OptionalFromRequestParts. A plain FromRequestParts implementation gives you no Option support, and the handler will not compile. Add the optional implementation yourself (see "Making Extraction Optional" above), or use Result<T, T::Rejection> if you need the failure details. Test optional extraction with a missing header to confirm you get None, and with a malformed header to confirm you still get a rejection.
Use &mut Parts for Inserting Extensions:
If your extractor wants to insert a value into parts.extensions for later extractors or handlers to use, you can do so because you have mutable access. This is a powerful technique for passing computed data along the request pipeline.
Summary and Decision Framework
FromRequestParts is the trait you use when building a custom extractor that only needs request metadata. It keeps the body untouched, allows the extractor to be placed before body-consuming extractors, and often leads to more modular, testable code.
To decide whether to use FromRequestParts or FromRequest, ask: Do I need to read the request body? If no, implement FromRequestParts. If yes, implement FromRequest. Most custom extractors for headers, tokens, tenant IDs, or shared state fall into the FromRequestParts bucket.
That one question is the whole decision framework for this page. A parts-only extractor keeps the body untouched, so it can sit anywhere in a handler signature and can be reused in middleware; a body extractor gives you the full request but must sit last and can only appear once. When you are unsure, start with FromRequestParts and switch to FromRequest only when you hit a concrete need for the body. For now, practice writing a few of your own extractors: extract a query parameter without using the built-in Query extractor, or read a custom header and parse a UUID. The more you write, the more natural the pattern becomes.