Warp vs Axum filter combinators
Compare how Warp uses filter combinators for routing and how Axum uses Router and handlers to achieve similar results, with beginner-friendly examples.
Two popular Rust web frameworks, Warp and Axum, solve the same problem in very different ways. Warp builds routes by chaining small pieces called filters with combinators. Axum uses a Router and ordinary Rust functions called handlers. This page explains the filter combinator approach, shows how Axum replaces it, and helps you understand the trade-offs when you see Warp code or need to choose between them.
What a Filter Is in Warp
In Warp, a filter is a small, reusable piece of logic that can do three things:
- Match part of an incoming request (like its path, method, or headers).
- Extract data from the request (like a path parameter, query string, or JSON body).
- Reject the request if the filter does not match.
A filter by itself is not a full route. It only handles one small aspect. For example, warp::path("hello") is a filter that matches any request whose path is exactly /hello. It does not care about the HTTP method, and it does not produce a response. Another filter, warp::get(), matches only GET requests.
To build an actual endpoint, you combine filters. That is where the name combinator comes from.
What a Combinator Is in Warp
A combinator is a method that takes one or more filters and produces a new filter. The most common ones are:
.and(other_filter)- both filters must match; data from both is combined..or(other_filter)- if the first filter rejects, try the second one..map(closure)- transform the extracted data into a response..then(async_closure)- like.map, but the closure can be async..boxed()- erase the concrete type, which helps when filter types become long.
Think of filters as building blocks and combinators as the glue. You start with a small filter, add another, add a transformation, and finally you have a filter that represents a complete route. Warp then passes that combined filter to warp::serve.
A minimal Warp route looks like this:
use warp::Filter;
#[tokio::main]
async fn main() {
let hello = warp::path("hello") // matches path "/hello"
.and(warp::get()) // only GET requests
.map(|| "Hello, World!"); // produce a response
warp::serve(hello)
.run(([127, 0, 0, 1], 3030))
.await;
}
Here, warp::path("hello") is one filter. .and(warp::get()) is a combinator that combines it with the method filter. The result is a filter that only matches GET requests to /hello. The .map() combinator then turns the matched request into a string response. Finally, warp::serve runs the filter as a server.
All the Warp examples on this page need the server feature enabled in Cargo.toml - warp::serve does not exist without it:
[dependencies]
warp = { version = "0.4", features = ["server"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
The Filter Trait:
Every filter in Warp implements the Filter trait. That trait has an Extract associated type and a Future that eventually yields either an extracted value or a rejection. When you chain filters, the extract types get combined into tuples. This is the core mechanism behind Warp's type safety, but it also makes filter types grow quickly in complexity.
How Axum Replaces Filters with a Router
Axum takes the opposite approach. Instead of composing tiny filters, you define routes by mapping a path and an HTTP method directly to a handler function. There are no filters to combine; the router itself matches the request and calls the right handler.
A handler is just an async function that returns something that can be turned into an HTTP response. The same /hello endpoint in Axum looks like this:
use axum::{Router, routing::get};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/hello", get(|| async { "Hello, World!" }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3030")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The Router::new().route("/hello", get(...)) line says: "for GET requests to /hello, run this closure". There is no chaining of filters, no .and() or .map() to combine pieces. The closure is an async function that returns a string, and Axum knows how to convert that string into an HTTP response.
You Have a Working Server:
If you run either of the two examples above, you can open http://127.0.0.1:3030/hello in a browser and see Hello, World!. Both frameworks produce the same observable result. The difference is only in how you expressed the route in code.
This directness is the main reason many developers find Axum easier to learn and read. You can look at a Router definition and immediately see every endpoint and its handler, without mentally unrolling a chain of combinators.
Extracting Path Parameters
Most APIs need to read values from the URL path, such as /users/42 where 42 is a user ID. In Warp, you use a path filter with a placeholder and then extract the value using .and() and .map() or .then().
Here is a Warp endpoint that extracts an integer user ID from the path:
use warp::Filter;
#[tokio::main]
async fn main() {
// path!("users" / u32) matches /users/<number> and extracts the number
let user = warp::path!("users" / u32)
.and(warp::get())
.map(|id: u32| format!("User ID: {}", id));
warp::serve(user).run(([127, 0, 0, 1], 3030)).await;
}
The path! macro lets you write a path pattern. Inside it, "users" / u32 means a literal users followed by a path segment that must be a u32. Warp parses the segment, and if it succeeds, the extracted u32 is passed to the closure in .map(). If the segment is not a valid number, Warp automatically rejects the request with a 404 Not Found.
Axum does the same thing using an extractor in the handler signature:
use axum::{Router, routing::get, extract::Path};
async fn user_handler(Path(id): Path<u32>) -> String {
format!("User ID: {}", id)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{id}", get(user_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3030")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Notice that the route string /users/{id} contains a named parameter {id}. Axum's router matches that segment and passes it to the handler as the Path<u32> extractor. The Path(id) syntax destructures the extractor to get the value. If the segment cannot be parsed as a u32, Axum returns a 400 Bad Request automatically.
Different Error Behavior for Invalid Input:
In Warp, an invalid path parameter (like /users/abc) causes the filter to reject, and Warp returns a 404 because no route matched. In Axum, the route itself matched, but the Path<u32> extractor failed to parse, so Axum returns a 400 Bad Request. This is a subtle but important difference when you are building error handling around invalid input.
Extracting Query Parameters
Query parameters are key-value pairs after the ? in a URL, like /search?q=rust&limit=10. Warp uses the warp::query filter to extract them. You can extract into a HashMap, but it is more common to define a struct that derives serde::Deserialize.
Here is a Warp endpoint that reads q and limit from the query string:
use warp::Filter;
use serde::Deserialize;
#[derive(Deserialize)]
struct SearchParams {
q: String,
limit: Option<u32>,
}
#[tokio::main]
async fn main() {
let search = warp::path("search")
.and(warp::get())
.and(warp::query::<SearchParams>())
.map(|params: SearchParams| {
let limit = params.limit.unwrap_or(10);
format!("Searching for '{}' with limit {}", params.q, limit)
});
warp::serve(search).run(([127, 0, 0, 1], 3030)).await;
}
The warp::query::<SearchParams>() filter attempts to parse the query string into a SearchParams struct. If the query string is missing or malformed, the filter rejects. The extracted struct is then available to the closure.
Axum provides a similar Query extractor. The handler receives a Query<SearchParams>:
use axum::{Router, routing::get, extract::Query};
use serde::Deserialize;
#[derive(Deserialize)]
struct SearchParams {
q: String,
limit: Option<u32>,
}
async fn search_handler(Query(params): Query<SearchParams>) -> String {
let limit = params.limit.unwrap_or(10);
format!("Searching for '{}' with limit {}", params.q, limit)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/search", get(search_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3030")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
In both frameworks, the query string is deserialized into a Rust struct. If a required field like q is missing, Warp rejects with a 400 response, and Axum returns a 400 as well. The main difference is again where the extraction happens: in the filter chain for Warp, and in the function arguments for Axum.
Handling JSON Bodies
For POST endpoints that receive JSON, Warp uses warp::body::json(). Axum uses the Json extractor. Both rely on serde for deserialization.
Warp example:
use warp::Filter;
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
name: String,
email: String,
}
#[tokio::main]
async fn main() {
let create_user = warp::path("users")
.and(warp::post())
.and(warp::body::json::<CreateUser>())
.map(|user: CreateUser| {
format!("Created user {} with email {}", user.name, user.email)
});
warp::serve(create_user).run(([127, 0, 0, 1], 3030)).await;
}
Axum equivalent:
use axum::{Router, routing::post, extract::Json};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
name: String,
email: String,
}
async fn create_user_handler(Json(user): Json<CreateUser>) -> String {
format!("Created user {} with email {}", user.name, user.email)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users", post(create_user_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3030")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
In Warp, if the JSON body is invalid or missing, the body::json filter rejects, and Warp returns a 400. In Axum, the Json extractor returns an error, and Axum also returns a 400. However, Axum's error handling is more uniform because all extractor failures go through the same FromRequest trait, whereas Warp has multiple rejection types that you may need to handle explicitly if you want custom error responses.
Side-by-Side: A Small REST API
To see the full difference, here is a simple REST API with two endpoints: GET /users/{id} and POST /users. Both frameworks will do the same thing. The Warp version is shown first, then the Axum version, and both use the dependencies shown above.
Warp:
use warp::Filter;
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
name: String,
email: String,
}
#[tokio::main]
async fn main() {
// GET /users/{id}
let get_user = warp::path!("users" / u32)
.and(warp::get())
.map(|id: u32| format!("User ID: {}", id));
// POST /users
let create_user = warp::path("users")
.and(warp::post())
.and(warp::body::json::<CreateUser>())
.map(|user: CreateUser| {
format!("Created user {} with email {}", user.name, user.email)
});
// Combine both routes with .or()
let routes = get_user.or(create_user);
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
}
Axum:
use axum::{Router, routing::{get, post}, extract::{Path, Json}};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
name: String,
email: String,
}
async fn get_user(Path(id): Path<u32>) -> String {
format!("User ID: {}", id)
}
async fn create_user(Json(user): Json<CreateUser>) -> String {
format!("Created user {} with email {}", user.name, user.email)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users/{id}", get(get_user))
.route("/users", post(create_user));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3030")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
In the Warp version, you build two separate filter chains and then combine them with .or(). That final routes filter is what you pass to warp::serve. The Axum version defines two handler functions and then registers both routes on the same Router. The router automatically handles method and path matching; no .or() needed.
Composability vs. Readability:
Warp's filters are extremely composable. You can extract a filter, store it in a variable, reuse it in multiple places, and combine it with other filters in different ways. Axum's router is more rigid: you register routes, and each route points to a single handler. However, that rigidity often makes Axum code easier to scan and understand at a glance, especially for large applications.
Common Mistakes and Misconceptions
Precedence in Warp's .and() and .or()
A frequent beginner mistake in Warp is misunderstanding how .and() and .or() associate. Both are method calls, so they evaluate left to right, and .or() does not bind tighter than .and(). If you write:
let routes = warp::path("users")
.and(warp::get())
.or(warp::path("posts"))
.and(warp::post());
You might read it as "GET /users, or POST /posts". But method calls are left-associative, so the expression is really ((users AND get) OR posts) AND post. The final .and(warp::post()) applies to the result of the whole .or(), not just to the second branch. The result is a filter that only matches POST requests: POST /posts matches, but GET /users never does, because a GET request fails the final post() check. The route you wanted silently never matches, and nothing warns you.
The fix is to build each branch on its own and combine them only at the end, so no .and() can reach across an .or():
let get_users = warp::path("users").and(warp::get());
let get_posts = warp::path("posts").and(warp::get());
let routes = get_users.or(get_posts);
This kind of subtle precedence error can lead to routes that never match or match incorrectly. Axum's router avoids this entirely because you explicitly list each route.
Filter Type Complexity Can Become Overwhelming:
In Warp, every .and() and .or() changes the type of the filter. As you add more layers, the type becomes a deeply nested chain of And, Or, Map, etc. The Rust compiler needs to know this exact type, and it can become so long that error messages become unreadable. You often have to call .boxed() to erase the type, which adds boilerplate. Axum's router hides most of this type complexity behind the Router type, and handler functions have simple signatures, making compile errors much more manageable.
Error Handling Differences
Warp's rejection system is powerful but can be confusing. Every filter can reject, and different rejections have different meanings (method not allowed, path not found, body parse error, etc.). To customize error responses, you must use recover or with to intercept rejections and convert them to replies. Axum centralizes errors through the FromRequest trait and the Result return type of handlers. To customize error responses, you typically implement IntoResponse for your error type or use middleware. For beginners, Axum's model is easier to grasp because errors are just normal Rust values in the handler, not a separate rejection stream.
Trying to Mix Warp and Axum
Because Warp and Axum are different frameworks built on different abstractions, you cannot directly use a Warp filter inside an Axum handler, or vice versa. Both are built on top of hyper, but their high-level APIs are incompatible. If you are moving from Warp to Axum, you will need to rewrite your route definitions and extraction logic. There is no automatic converter.
Don't Assume a 1-to-1 Mapping:
Warp's filter combinators do not have a direct equivalent in Axum. You cannot just translate .and(warp::query::<T>()) to a line in Axum; the query extraction moves into the handler's parameter list. When reading Warp code, focus on what each filter extracts and what the final .map() or .then() does with that data. Then rewrite that logic as a handler function with the appropriate extractors.
When to Prefer One Approach Over the Other
Warp's filter model excels when you need very fine-grained control over routing and reuse. For example, you can define a filter that extracts an authentication token, then use .and(auth_filter) in many different routes. You can also easily branch with .or() for complex matching rules. However, the cognitive overhead of tracking filter types and rejection behavior grows quickly.
Axum's router model is more straightforward. It is often a better choice for:
- Teams where readability and quick onboarding matter.
- Typical REST APIs or JSON backends with standard route shapes.
- Applications that rely heavily on compile-time checks for extractor validity.
Axum also benefits from a larger ecosystem of middleware (via tower-http) that works directly with its Service-based architecture. Warp is built directly on Hyper, not on Tower, so tower-http layers do not plug into it the way they plug into Axum.
For absolute beginners, Axum is generally easier to start with because you can write a handler as a normal function and not worry about chaining filters. Once you understand Axum's extractor pattern, moving to Warp later is possible, but the reverse can feel like a step down in readability.
Summary
Warp and Axum represent two different philosophies for defining web routes in Rust. Warp treats routing as a composition of small filters connected by combinators like .and(), .or(), and .map(). Axum replaces that with a Router that maps paths to ordinary handler functions, and extraction of request data happens through function parameters using types like Path, Query, and Json.
The same endpoint can be expressed with both, but the mental models are distinct. Warp's filters offer high composability but come with type complexity and rejection-handling challenges. Axum's router prioritizes clarity and compile-time safety, making it a popular choice for new projects.
If you are coming from Warp, the key shift is to stop thinking in terms of chained filters and start thinking in terms of separate handler functions with well-defined extractor arguments. Most routing logic that Warp encodes with .and() and .or() becomes a list of .route() calls on a Router. The extraction logic moves from the filter chain into the function signature. Once you make that shift, Axum's code often feels simpler and easier to maintain.