Warp vs Axum Router and Handlers

Compare how routing and handler functions work in Axum and Warp, with examples of path parameters, methods, and request extraction.

Warp builds routes using filter combinators. Here we put the two frameworks side by side on the specific task of defining where a request goes and what code runs when it gets there. In web development, routing is the process of matching an incoming HTTP request's path and method (GET, POST, etc.) to a specific piece of code, and a handler is that piece of code. Axum and Warp both solve this problem, but the mental model behind each one is quite different. Axum gives you a dedicated Router object with a clear, tree-like structure. Warp asks you to build up a single big filter expression where each piece describes a condition or a transformation. Understanding this difference will help you read, write, and debug code in both frameworks.

The Core Mental Models

At the most basic level, a web server receives an HTTP request and must decide which function to call. Axum and Warp approach that decision in opposite directions.

With Axum, you start with an empty Router. You then register routes on it using the .route() method. Each route is attached to a specific path and one or more HTTP methods. The Router holds all of these registrations in a structure that Axum can efficiently search when a request arrives.

With Warp, you build a filter. A filter is an object that either accepts a request or rejects it. You combine small filters using .and() to require multiple conditions, .or() to allow alternatives, and .and_then() to attach a handler. The final filter becomes your entire application.

Let's see the smallest possible example in both.

Minimal GET route

Axum - create a router, add a route for GET /, and serve it.

// src/main.rs
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(|| async { "Hello, Axum!" }));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    println!("Listening on http://localhost:3000");
    axum::serve(listener, app).await.unwrap();
}

Warp - create a filter that matches the root path and a GET request, then attach a handler.

// src/main.rs
use warp::Filter;
#[tokio::main]
async fn main() {
    let hello = warp::path::end()
        .and(warp::get())
        .map(|| "Hello, Warp!");
    println!("Listening on http://localhost:3000");
    warp::serve(hello).run(([0, 0, 0, 0], 3000)).await;
}

All the Warp examples on this page need the server feature enabled, or warp::serve will not exist:

[dependencies]
warp = { version = "0.4", features = ["server"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }

Both programs do exactly the same thing. But look at the shape: Axum creates a Router and calls a method; Warp builds a pipeline of filters ending with .map(). In Axum, the handler is passed as an argument to get(). In Warp, the handler is attached with .map() after all the condition filters.

Route vs Filter:

Axum's Router is an immutable builder value: each .route() call consumes the router and returns a new one with the route added, so you build it up by chaining calls. Warp's filter is also an immutable value: you combine smaller values into a bigger one. This distinction influences every other aspect of working with the two frameworks.

The contrast in one sentence: in Axum, routes are registered up front - you build the whole routing table when the server starts, and each request is matched against that finished table. In Warp, filters compose per request - the filter chain itself is the routing logic, and every request flows through the chain from the first filter to the last, with each filter deciding whether to accept, transform, or reject it. That is why Axum can answer "which routes exist?" by inspecting the Router, while in Warp the answer only exists inside the composed filter value - and why Warp's .or() order matters (the first matching filter wins) while Axum's route registration order does not.

Paths and HTTP Methods

Real applications need more than one route. Let's add a few endpoints and compare how each framework expresses them.

Multiple routes in Axum

In Axum, every path string can have one or more method routers chained onto it with .get(), .post(), etc. Different paths are added with separate .route() calls.

// src/main.rs
use axum::{routing::{get, post}, Router};
async fn home() -> &'static str { "Home page" }
async fn about() -> &'static str { "About page" }
async fn create_user() -> &'static str { "User created" }
async fn list_users() -> &'static str { "List of users" }
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home))
        .route("/about", get(about))
        .route("/users", get(list_users).post(create_user));
    // ... serve the app
}

Multiple routes in Warp

Warp expresses alternatives with .or(). Each alternative is a complete filter that can match a request. The order matters: the first matching filter wins. This makes the code read from top to bottom as a list of "if this, then that". The examples below use the same server feature dependency shown above.

// src/main.rs
use warp::Filter;
fn home() -> &'static str { "Home page" }
fn about() -> &'static str { "About page" }
fn create_user() -> &'static str { "User created" }
fn list_users() -> &'static str { "List of users" }
#[tokio::main]
async fn main() {
    let home_route = warp::path::end()
        .and(warp::get())
        .map(home);
    let about_route = warp::path("about")
        .and(warp::path::end())
        .and(warp::get())
        .map(about);
    let users_list = warp::path("users")
        .and(warp::path::end())
        .and(warp::get())
        .map(list_users);
    let users_create = warp::path("users")
        .and(warp::path::end())
        .and(warp::post())
        .map(create_user);
    let routes = home_route
        .or(about_route)
        .or(users_list)
        .or(users_create);
    warp::serve(routes).run(([0, 0, 0, 0], 3000)).await;
}

The handlers here are plain fn, not async fn. That is deliberate: .map() expects a function that returns a Reply directly, and an async fn returns a future, which is not a Reply. If your handler needs to do async work, use .and_then() instead, which accepts an async function returning Result<impl Reply, Rejection>.

Notice how in Warp, the path users appears twice, once for GET and once for POST, and each uses warp::path::end() to ensure the path ends there. In Axum, the path users is written once and the two methods are chained.

Warp filter order matters:

In Warp, filters are tested in the order they appear in the .or() chain. If you have two filters that could both match a request, the first one wins. For example, if you put a more general filter before a more specific one, the specific one may never be reached. Axum does not have this pitfall because routing is based on a tree structure, not a linear scan.

Path Parameters

Most APIs include dynamic segments in the URL, like /users/42 or /posts/some-title. Both frameworks support extracting these values and passing them to your handler.

Axum path parameters

Axum 0.8 changed the syntax for path parameters from :param to {param} to align with OpenAPI and Rust's formatting macros. Inside the route string, you write a placeholder in curly braces. The handler then accepts a Path extractor that contains the value.

// src/main.rs
use axum::{extract::Path, routing::get, Router};
async fn get_user(Path(user_id): Path<u64>) -> String {
    format!("You asked for user {}", user_id)
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users/{user_id}", get(get_user));
    // ... serve
}

For multiple parameters, use a tuple.

// src/main.rs
use axum::{extract::Path, routing::get, Router};
async fn get_comment(
    Path((post_id, comment_id)): Path<(u64, u64)>,
) -> String {
    format!("Post {}, comment {}", post_id, comment_id)
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/posts/{post_id}/comments/{comment_id}", get(get_comment));
    // ... serve
}

Warp path parameters

Warp uses separate filter components for each parameter: warp::path::param::<T>(). You combine them in the same order as they appear in the URL. The parameter values are then passed to the handler as a tuple in the .and_then() closure.

// src/main.rs
use warp::Filter;
async fn get_user(user_id: u64) -> String {
    format!("You asked for user {}", user_id)
}
#[tokio::main]
async fn main() {
    let user_route = warp::path("users")
        .and(warp::path::param::<u64>())
        .and(warp::path::end())
        .and(warp::get())
        .and_then(|user_id| async move { Ok(get_user(user_id).await) });
    warp::serve(user_route).run(([0, 0, 0, 0], 3000)).await;
}

For two parameters, you chain two param filters and the handler receives both values.

// src/main.rs
use warp::Filter;
async fn get_comment(post_id: u64, comment_id: u64) -> String {
    format!("Post {}, comment {}", post_id, comment_id)
}
#[tokio::main]
async fn main() {
    let comment_route = warp::path("posts")
        .and(warp::path::param::<u64>())
        .and(warp::path("comments"))
        .and(warp::path::param::<u64>())
        .and(warp::path::end())
        .and(warp::get())
        .and_then(|post_id, comment_id| async move {
            Ok(get_comment(post_id, comment_id).await)
        });
    warp::serve(comment_route).run(([0, 0, 0, 0], 3000)).await;
}

Old Axum syntax panics at startup:

If you copy code from an old tutorial, you might see route strings like /users/:id or /files/*path. Those syntaxes are no longer valid in Axum 0.8 - and they do not fail at compile time. Registering them panics when the Router is built, so the server crashes on startup. Always use {id} for single parameters and {*path} for wildcards.

The way the handler receives values is the biggest contrast: Axum passes them as typed arguments using extractors that the compiler checks. Warp passes them as a tuple from the filter chain - you must destructure them in the closure and explicitly call your handler. That extra step is part of Warp's functional style: the filter does the extraction, and .and_then() bridges to your async function.

Handler Signatures and Return Types

The signature of a handler is where the two frameworks diverge sharply. Understanding what each one expects will save you hours of compiler errors.

Axum handlers

An Axum handler can be any async function that:

  • Takes zero or more extractor arguments (we'll cover those soon).
  • Returns a type that implements the IntoResponse trait.

IntoResponse is implemented for many common types: &'static str, String, StatusCode, Json<T>, Html<T>, and even tuples like (StatusCode, Json<T>). You can also return Result<T, E> where both T and E implement IntoResponse - that's how you do error handling.

use axum::{http::StatusCode, Json, response::Html};
use serde_json::{json, Value};
async fn plain_text() -> &'static str {
    "Hello"
}
async fn no_content() -> StatusCode {
    StatusCode::NO_CONTENT
}
async fn json_response() -> Json<Value> {
    Json(json!({ "message": "Hello" }))
}
async fn html_response() -> Html<&'static str> {
    Html("<h1>Hello</h1>")
}
// Returning a Result lets you handle errors
async fn maybe_error(flag: bool) -> Result<&'static str, StatusCode> {
    if flag {
        Ok("Success")
    } else {
        Err(StatusCode::BAD_REQUEST)
    }
}

Because Axum handlers are just functions with typed signatures, the compiler can tell you exactly what's wrong when something doesn't implement the required traits.

Warp handlers

In Warp, a handler is not a standalone function you register. It is a closure or function that you attach to a filter using .map(), .and_then(), or .then(). The return type must be something that implements the Reply trait, or a Result<impl Reply, Rejection> when using .and_then().

The most common pattern is to use .and_then() and return Ok(reply), where reply is any type that implements Reply. Warp provides warp::reply::html(), warp::reply::json(), and others, or you can use warp::reply::with_status().

use warp::{Filter, reply::{self, Reply}, http::StatusCode};
async fn plain_text() -> &'static str {
    "Hello"
}
async fn json_response() -> impl Reply {
    reply::json(&serde_json::json!({ "message": "Hello" }))
}
async fn maybe_error(flag: bool) -> Result<impl Reply, warp::Rejection> {
    if flag {
        Ok(reply::with_status("Success", StatusCode::OK))
    } else {
        Err(warp::reject::not_found())
    }
}
// Building a filter that uses maybe_error
let route = warp::path("check")
    .and(warp::query::<std::collections::HashMap<String, String>>())
    .and_then(|params: std::collections::HashMap<String, String>| {
        let flag = params.get("flag").map(|s| s == "true").unwrap_or(false);
        maybe_error(flag)
    });

Notice that the return type is often Result<impl Reply, Rejection>. The Rejection type is Warp's way of representing an error. You can create custom rejections, but that is a topic for error handling pages.

Warp handler functions are not directly registered:

A common beginner mistake is to try to pass a plain async function to warp::path().and(warp::get()).map(my_handler) and expect it to work. The function must return a Reply (or, with .and_then(), a Result<impl Reply, Rejection>). A String already implements Reply - it is returned as text/plain - so .map(|| "hello".to_string()) works with no wrapping at all. What does not work is returning a type with no Reply implementation, such as a custom struct: then you must convert it yourself (for example with warp::reply::json(...)) or implement Reply for it.

Extracting Data from Requests

Real handlers need to read data from the incoming request: path parameters, query strings, JSON bodies, headers. Axum and Warp both provide mechanisms, but the way you declare what you need is different.

Axum extractors

In Axum, you declare extractors as arguments to your handler function. Axum will automatically run each extractor, and if any of them fail, it returns a 400 or 500 response before your handler runs. The compiler ensures that the order of extractors is valid: only one extractor can consume the request body, and it must be the last argument.

use axum::{
    extract::{Path, Query, Json},
    http::StatusCode,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct Pagination {
    page: Option<u32>,
    per_page: Option<u32>,
}
#[derive(Deserialize)]
struct CreateUser {
    name: String,
    email: String,
}
async fn create_user(
    Path(team_id): Path<u64>,
    Query(pagination): Query<Pagination>,
    Json(payload): Json<CreateUser>,
) -> StatusCode {
    // ...
    StatusCode::CREATED
}

You can also use State to access shared application state, but that is a different topic.

Warp extractors

In Warp, extraction is done by filters that produce a value. You chain them with .and(), and the handler receives a tuple of those values in the same order. For query parameters and JSON bodies, you use warp::query() and warp::body::json() filters.

use warp::Filter;
use serde::Deserialize;
#[derive(Deserialize)]
struct Pagination {
    page: Option<u32>,
    per_page: Option<u32>,
}
#[derive(Deserialize)]
struct CreateUser {
    name: String,
    email: String,
}
async fn create_user(
    team_id: u64,
    pagination: Pagination,
    payload: CreateUser,
) -> impl warp::Reply {
    // ...
    warp::reply::with_status("created", warp::http::StatusCode::CREATED)
}
#[tokio::main]
async fn main() {
    let route = warp::path("teams")
        .and(warp::path::param::<u64>())
        .and(warp::query::<Pagination>())
        .and(warp::body::json::<CreateUser>())
        .and(warp::path::end())
        .and(warp::post())
        .and_then(|team_id, pagination, payload| async move {
            Ok(create_user(team_id, pagination, payload).await)
        });
    warp::serve(route).run(([0, 0, 0, 0], 3000)).await;
}

The filter chain mirrors the handler's parameter list: the first param corresponds to team_id, the query to pagination, and the body::json to payload. If any filter rejects, the whole chain stops and Warp returns an error response.

Both approaches are type-safe:

In Axum, the compiler verifies that each extractor implements FromRequestParts or FromRequest and that their order is valid. In Warp, the compiler verifies that each filter produces the expected type and that .and_then() receives the right tuple. In both cases, many errors are caught before you even run the server.

Organizing Larger Applications

As your app grows, you need a way to split routes into modules or separate functions. Axum and Warp both support this, but the mechanisms look different.

Axum: nested routers and merging

Axum provides Router::nest() to mount a sub-router under a path prefix. This is extremely helpful for grouping related routes, like all user-related endpoints under /api/users. You can also use Router::merge() to combine two routers that already define their own full paths.

// src/main.rs
use axum::{routing::{get, post}, Router};
fn user_routes() -> Router {
    Router::new()
        .route("/", get(list_users).post(create_user))
        .route("/{id}", get(get_user).put(update_user).delete(delete_user))
}
fn health_routes() -> Router {
    Router::new().route("/health", get(|| async { "OK" }))
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .nest("/api/users", user_routes())
        .merge(health_routes());
    // ... serve
}

Warp: combining filters with .or()

Warp does not have a built-in nesting concept. You combine filters with .or() and each filter includes its full path. To keep code organized, you typically define each route as a separate filter variable, then combine them in a routes() function.

// src/main.rs
use warp::Filter;
fn user_routes() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
    let list = warp::path("users")
        .and(warp::path::end())
        .and(warp::get())
        .map(|| "list users");
    let get_one = warp::path("users")
        .and(warp::path::param::<u64>())
        .and(warp::path::end())
        .and(warp::get())
        .map(|id: u64| format!("user {}", id));
    let create = warp::path("users")
        .and(warp::path::end())
        .and(warp::post())
        .map(|| "created");
    list.or(get_one).or(create)
}
fn health_route() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
    warp::path("health")
        .and(warp::path::end())
        .and(warp::get())
        .map(|| "OK")
}
#[tokio::main]
async fn main() {
    let routes = user_routes().or(health_route());
    warp::serve(routes).run(([0, 0, 0, 0], 3000)).await;
}

The return type impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone is verbose but necessary for composition. Axum's Router is a concrete type that is always cloneable and combinable, which makes the code cleaner.

Error Handling

Error handling in web frameworks is about what happens when something goes wrong inside a handler. Both Axum and Warp let you return a Result type, but the error type and how you convert it to an HTTP response differ.

Axum: Result<T, E> where E: IntoResponse

In Axum, if your handler returns Result<T, E>, Axum will use IntoResponse for both T and E. For Ok, the value is converted to a successful response. For Err, the error is converted to an error response. This means you can use any type that implements IntoResponse as the error, including StatusCode, (StatusCode, String), or a custom error type that you implement IntoResponse for.

use axum::{http::StatusCode, response::{IntoResponse, Response}};
struct AppError;
impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        (StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong").into_response()
    }
}
async fn handler(flag: bool) -> Result<&'static str, AppError> {
    if flag {
        Ok("Success")
    } else {
        Err(AppError)
    }
}

Warp: Result<impl Reply, Rejection>

Warp handlers return Result<impl Reply, Rejection>. If you return Err(rejection), Warp will turn that rejection into a response using its default rejection handler. You can also define custom rejections by implementing the Reject trait and then providing a custom recover filter to convert them into replies. This is more involved than Axum's IntoResponse.

use warp::{Filter, reject::Reject, Rejection, Reply, http::StatusCode};
#[derive(Debug)]
struct AppError;
impl Reject for AppError {}
async fn handler(flag: bool) -> Result<impl Reply, Rejection> {
    if flag {
        Ok(warp::reply::with_status("Success", StatusCode::OK))
    } else {
        Err(warp::reject::custom(AppError))
    }
}
// To recover from AppError and produce a custom response:
let route = warp::path("check")
    .and(warp::get())
    .and_then(|| handler(true))
    .recover(|err: Rejection| async move {
        if let Some(_) = err.find::<AppError>() {
            Ok(warp::reply::with_status("Custom error", StatusCode::BAD_REQUEST))
        } else {
            Err(err)
        }
    });

For beginners, Axum's error model is easier to understand because everything is based on IntoResponse, which you already use for success responses.

Conceptual alignment:

Axum's IntoResponse unifies success and error paths - both are just conversions to an HTTP response. Warp splits them into Reply for success and Rejection for failure, and requires a separate recover step to customize errors. This is a key architectural difference to keep in mind.

Common Mistakes and How to Avoid Them

When moving between Axum and Warp (or learning either for the first time), certain mistakes appear again and again. Recognizing them early will save you time.

  1. In Axum, forgetting that a handler must return something that implements IntoResponse. The unit type () does implement IntoResponse - it produces an empty 200 OK response - so a handler that only performs a side effect can simply return nothing (async fn handler() { ... }). What fails is returning a type with no IntoResponse implementation, such as a plain custom struct: then the compiler complains that the return type does not implement IntoResponse. If you want a different status, return StatusCode::NO_CONTENT explicitly, which is usually clearer than an empty 200.
  2. In Axum, using the old path parameter syntax. As of Axum 0.8, :param and *param no longer work - but they do not produce a compiler error. A route like /users/:id panics at registration when the Router is built, crashing the server at startup. Always use {param} and {*param}. If the server panics on startup with "Path segments must not start with :", check your colons and asterisks.
  3. In Warp, mixing up .map() and .and_then(). .map() is for synchronous transformations that always succeed. .and_then() is for async operations that may fail (return a Result). If you use .map() with a function that returns a Result, you'll get a type error because map expects a Reply, not a Result.
  4. In Warp, forgetting .and(warp::path::end()). Without it, a filter like warp::path("users") will also match /users/anything/else because it only checks the first segment. Always add path::end() after your final path segment unless you intentionally want a prefix match.
  5. In Warp, chaining filters in the wrong order. Filters are checked sequentially with .or(). If you have a filter that matches /users/{id} before /users/me, the {id} filter will capture "me" as an id, and the specific route will never be reached. Order matters.
  6. In both frameworks, trying to extract the body more than once. The HTTP body can only be read once. In Axum, only one extractor that consumes the body is allowed, and it must be last. In Warp, if you try to use warp::body::json() twice, the second will fail because the body is already consumed. Use one body extractor and pass the data where needed.
  7. In Warp, not understanding the tuple returned by filters. Each filter you add with .and() contributes one value to the tuple. If you add param::<u64>() and query::<Pagination>(), the handler receives (u64, Pagination). A mismatch in the tuple arity or types will cause a compiler error. Pay attention to the exact number and order of filters.

Compiler errors can be intimidating:

Both Axum and Warp rely heavily on generics and traits. A small mistake can produce a long error message with many type names. Instead of reading every line, look for the part that says "the trait X is not implemented for Y" - that tells you what you forgot or mismatched. Axum 0.8 has improved diagnostics that often point directly to the problem.

Which One Should You Use?

This page is not about picking a winner, but about understanding the trade-offs. Axum's router model feels more familiar to developers coming from Express, Flask, or other traditional web frameworks. You define routes explicitly, and the framework handles matching and extraction invisibly. Warp's filter model is more functional and composable, but it requires you to think in terms of filter pipelines and tuple outputs.

If you value clarity, explicit route definitions, and a shallow learning curve, Axum is often the easier choice. If you enjoy functional composition and want to build reusable filter pieces, Warp's approach can be very expressive - but it comes with more type complexity and a steeper learning curve for beginners.

You can succeed with either:

Both frameworks are production-ready and used in real systems. The key is to pick the one whose mental model you can hold in your head while debugging. Many teams choose Axum because its Router is easy to read and reason about at a glance, even in large codebases.

Summary

This page compared how routing and handlers work in Axum and Warp. Axum uses a Router object where you register paths and methods explicitly, and handlers are async functions with typed extractor arguments. Warp uses composable filters where you combine path, method, and extraction filters, then attach a handler with .map() or .and_then(). Path parameters, request extraction, and error handling all follow these two different mental models.

The most important insight is that Axum centralizes routing logic in a dedicated structure, while Warp distributes it across a chain of filters. That single difference drives everything else - how you organize code, how you pass data to handlers, and how you handle errors. When you move from one framework to the other, don't just translate syntax; translate the shape of the application.

For the next step, you may want to explore how each framework handles application state - shared data like database connections or configuration that many handlers need. That topic builds directly on the handler signature ideas introduced here.