Axum as HTTP Routing Library

How the Router type matches incoming HTTP requests to the correct handler functions using a clean macro-free API

Axum as HTTP Routing Library

Every web server has the same basic job at its core. A request arrives with a method like GET or POST and a path like /users or /about. The server has to look at that method and path, then decide which piece of code should run in response. That decision process is called routing.

Axum is described in its official documentation as "an HTTP routing and request-handling library." The routing half of that description is what this page covers. The Router type is the component that holds your route table and performs the matching. Without it, you would be writing manual string comparisons against every incoming request path.

How a Web Server Decides What Code to Run

Imagine a user opens a browser and visits http://localhost:3000/users. The browser sends an HTTP request to your server. That request carries at least two pieces of information you care about for routing: the method (in this case GET) and the path (in this case /users).

Your server code receives those two strings. Now it has to answer one question: which function should handle this request? If the path is /users and the method is GET, maybe the function should return a list of users. If the path is /users and the method is POST, maybe a different function should create a new user. The path /users/42 might need yet another function that fetches a single user with ID 42.

A routing library automates this matching. You declare the mapping between "method + path pattern" and the function that should run. The library then inspects every incoming request, finds the matching declaration, and invokes the right function for you.

Writing Route Matching by Hand

To understand why a routing library is useful, it helps to see what the alternative looks like. Without any framework, you would write a function that receives the method and path, then manually compares them against every route you care about.

Here is a simplified version of what that manual matching might look like:

// A hand-written routing attempt - do not do this in real projects
fn handle_request(method: &str, path: &str) -> String {
    if method == "GET" && path == "/" {
        "Welcome to the home page".to_string()
    } else if method == "GET" && path == "/about" {
        "This is the about page".to_string()
    } else if method == "POST" && path == "/users" {
        "Creating a new user".to_string()
    } else if method == "GET" && path.starts_with("/users/") {
        let id = &path[7..];
        format!("Fetching user with id {id}")
    } else {
        "404 - not found".to_string()
    }
}

This works for three or four routes. Now imagine a real application with fifty routes, some with multiple path parameters, some with wildcard matching, some nested under /api/v1, and some that only respond to specific HTTP methods. The if-else chain grows into a tangled mess. Adding a new route means finding the right spot in a long conditional chain and hoping you did not break an existing match.

The deeper problem is that this manual approach gives you no help with parsing. In the example above, extracting the id from /users/42 required slicing the string at a hard-coded byte offset. If the path is /users/ with nothing after it, that slice panics. A proper routing library handles these edge cases for you.

Axum's Router as a Route Table

Axum solves this with a type called Router. You can think of a Router as a table that maps route patterns to handler functions. You build the table before the server starts, then hand the finished Router to Axum's server code. From that point on, every incoming request is matched against the table automatically.

The key design choice in Axum is that the Router is built using ordinary method calls. There are no special attributes above your handler functions, no code generation, and no macros that rewrite your source. You write plain Rust:

use axum::{routing::get, Router};
async fn home() -> &'static str {
    "Welcome"
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

This is the complete structure of a minimal Axum routing setup. Router::new() creates an empty route table. The .route("/", get(home)) call adds one entry: when a GET request arrives for the path /, invoke the home function. The method chaining style means you can keep adding .route() calls to build up a larger table.

Routing Is Working:

When you run this code and visit http://localhost:3000/ in a browser, you should see the text Welcome displayed. That response means the Router matched the incoming GET / request and called the home function.

The Smallest Routing Example

Let us break down the minimal example piece by piece, because every part appears in virtually every Axum routing setup you will write.

The first line imports two things from the axum crate:

use axum::{routing::get, Router};

Router is the type you build. The routing module contains functions named after HTTP methods - get, post, put, delete, patch, and others. Each of those functions wraps a handler function and tells the Router which HTTP method the route responds to.

The handler function is just an async function:

async fn home() -> &'static str {
    "Welcome"
}

For routing purposes, the handler does not need any special signature. It can return a string, and Axum will convert that into a proper HTTP response later. The routing table only cares that it receives a function it can call when a matching request arrives.

Inside main, the #[tokio::main] attribute marks the function as the entry point for Tokio's async runtime. Axum depends on Tokio to handle network I/O, so this attribute is required for every Axum application. The runtime is what allows your handler to use async and await.

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Router::new() starts with an empty table. .route("/", get(home)) adds one entry. Then a TcpListener is bound to port 3000, which means the server will accept connections on that port. Finally, axum::serve(listener, app) hands your finished Router to the server and starts listening.

The routing Module Has One Function Per HTTP Method:

You will see get, post, put, delete, patch, head, options, and trace in the axum::routing module. Each one corresponds to an HTTP method of the same name. When you call get(home), you are saying "match GET requests only." A POST request to the same path will not match this route - the path matches, but the method does not, so the response is 405 Method Not Allowed.

Building a Larger Route Table

One route is not enough for any real application. The chaining API makes it straightforward to add many routes:

use axum::{routing::get, Router};
async fn home() -> &'static str {
    "Home page"
}
async fn about() -> &'static str {
    "About page"
}
async fn contact() -> &'static str {
    "Contact page"
}
async fn blog_index() -> &'static str {
    "All blog posts"
}
async fn blog_post() -> &'static str {
    "A single blog post"
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home))
        .route("/about", get(about))
        .route("/contact", get(contact))
        .route("/blog", get(blog_index))
        .route("/blog/post", get(blog_post));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Each .route() call adds a new entry to the table. The first argument is the path pattern, the second is a method handler. Axum matches requests by precedence, not by the order routes were added: a static segment beats a capture, so a route for /foo takes precedence over /{key} for a request to /foo, whichever was registered first. For most practical purposes with distinct paths, the order does not matter.

What matters is that the Router now responds to five different paths. Visiting /about returns "About page", visiting /blog/post returns "A single blog post", and so on. Each route is fully independent. Adding a sixth route does not require touching any of the existing ones.

Matching Different HTTP Methods on One Path

Real APIs often need the same path to behave differently depending on the HTTP method. A GET /users request should list users, while a POST /users request should create one. Axum lets you chain method handlers on a single .route() call:

use axum::{
    routing::{get, post},
    Router,
};
async fn list_users() -> &'static str {
    "Returning all users"
}
async fn create_user() -> &'static str {
    "Creating a new user"
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users", get(list_users).post(create_user));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The .post(create_user) call is chained directly onto get(list_users). Both method handlers are attached to the same path /users. When a GET /users request arrives, list_users runs. When a POST /users request arrives, create_user runs. If a DELETE /users request arrives, the path matches but no handler is registered for DELETE, so Axum returns a 405 Method Not Allowed response (with an Allow header listing the methods the path does support), not a 404. A 404 Not Found is only for a path that matches no route at all.

Method Chains Can Get Long:

Chaining many methods on one path is convenient but can make a single .route() call hard to read. If a path needs more than three methods, consider splitting the chains across multiple lines or grouping related methods together. The route table behaves the same way regardless of how you format the chain.

Routes with Variable Segments

So far every path has been a fixed string. But real routes often contain variables. A user profile page might live at /users/alice, /users/bob, and /users/carol - the path has the same structure but a different value in the final segment.

Axum handles this with path parameters. The syntax in Axum 0.8 uses curly braces:

use axum::{
    extract::Path,
    routing::get,
    Router,
};
async fn get_user(Path(user_id): Path<u64>) -> String {
    format!("Fetching user with id {user_id}")
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users/{user_id}", get(get_user));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The route pattern /users/{user_id} contains {user_id} as a placeholder. When a request arrives at /users/42, the Router matches the pattern and captures 42 as the value of user_id. That captured value is then made available to the handler through the Path extractor, which this handler receives as Path<u64>.

The handler's first argument is Path(user_id): Path<u64>. The Path type wraps the captured parameter. Inside the function body, user_id is a plain u64 with the value 42. Axum converted the string "42" from the URL into the numeric type automatically.

Path Syntax Changed in Axum 0.8:

Older versions of Axum used a colon-based syntax: /users/:id. Axum 0.8 replaced that with curly braces: /users/{id}. The old syntax no longer works in the latest version - registering a route whose segment starts with : panics at startup unless you first call Router::without_v07_checks(), which turns the v0.7 compatibility checks off for that router. If you are reading code examples from older tutorials and see a route like /users/:id, mentally convert it to /users/{id}.

Multiple Path Parameters

A path can contain more than one parameter. Consider an API that manages comments on blog posts. The route /posts/{post_id}/comments/{comment_id} targets a single comment on a single post:

use axum::{
    extract::Path,
    routing::get,
    Router,
};
async fn get_comment(
    Path((post_id, comment_id)): Path<(u64, u64)>,
) -> String {
    format!("Post {post_id}, Comment {comment_id}")
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/posts/{post_id}/comments/{comment_id}", get(get_comment));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The pattern captures two values. The Path extractor uses a tuple (u64, u64) to receive both, in the same order they appear in the path. A request to /posts/10/comments/25 results in post_id being 10 and comment_id being 25.

The key routing idea here is that the pattern is still a single string. /posts/{post_id}/comments/{comment_id} matches any two-segment path that has the fixed segments posts and comments at the right positions. The variable parts are in between.

Type Conversion Can Fail

The Path<u64> extractor tries to convert the captured string into a u64. What happens if a request arrives at /users/not-a-number? The string "not-a-number" cannot be parsed as a u64. In that case, the extractor fails, and Axum responds with a 400 Bad Request status automatically.

Choosing the Wrong Type Breaks Route Matching:

If you declare Path<u64> but a request sends a non-numeric value, Axum returns 400 Bad Request and your handler never runs. This is a deliberate design choice - the routing layer validates the URL segment type before your application code executes. Choose the parameter type that matches what clients are expected to send. Use String if the value can be arbitrary text.

Wildcard Routes for Catch-All Paths

Sometimes you need a route that matches any number of path segments after a certain point. A file serving route might need to handle /files/images/logo.png and /files/docs/readme.txt and /files/anything/else/here. Hard-coding every possible pattern is impossible.

Axum supports wildcard parameters using the {*name} syntax:

use axum::{
    extract::Path,
    routing::get,
    Router,
};
async fn serve_file(Path(file_path): Path<String>) -> String {
    format!("Serving file at {file_path}")
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/files/{*path}", get(serve_file));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The pattern /files/{*path} matches /files/ followed by one or more segments - one segment, many segments - but it does not match /files or /files/ on their own: a wildcard never matches an empty remainder. The captured value is the entire remainder of the path after /files/. A request to /files/images/logo.png yields path equal to "images/logo.png". A request to /files/a/b/c/d yields "a/b/c/d". If you also need /files itself to respond, register it as a separate route.

Wildcards are useful for serving static content, building proxy endpoints, or handling any URL structure you cannot enumerate in advance. The captured value is always a String - there is no type conversion involved, because the wildcard can be arbitrary text.

Nesting Routers to Organize Large Applications

As your application grows, a single flat list of .route() calls becomes unwieldy. Imagine an API with fifty user-related routes, thirty product-related routes, and twenty order-related routes. Putting all one hundred .route() calls in one place makes the code hard to navigate.

Axum allows you to build separate Router instances and nest them under a common path prefix. The .nest() method attaches one Router under another:

use axum::{
    routing::{get, post},
    Router,
};
async fn list_users() -> &'static str {
    "Listing all users"
}
async fn create_user() -> &'static str {
    "Creating a user"
}
async fn get_user() -> &'static str {
    "Getting one user"
}
async fn delete_user() -> &'static str {
    "Deleting a user"
}
#[tokio::main]
async fn main() {
    // A Router dedicated to user-related routes
    let user_routes = Router::new()
        .route("/", get(list_users).post(create_user))
        .route("/{id}", get(get_user).delete(delete_user));
    // The main Router nests the user Router under /users
    let app = Router::new()
        .nest("/users", user_routes);
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The user_routes Router defines routes relative to /users. Its root route / corresponds to GET /users and POST /users after nesting. Its /{id} route corresponds to GET /users/{id} and DELETE /users/{id}. The .nest("/users", user_routes) call prepends /users to every route inside user_routes.

Nested Routes Keep Paths Relative:

Inside a nested Router, paths are relative to the nesting prefix. You write "/" not "/users", and "/{id}" not "/users/{id}". The parent Router adds the prefix when matching incoming requests. This makes nested routers reusable - you could nest the same user_routes Router under a different prefix without changing its internal route definitions.

Merging Multiple Routers

Sometimes you do not want a common prefix. You might have routes defined in separate modules, each with full paths, and you want to combine them into one route table without prefixing. The .merge() method handles this:

use axum::{routing::get, Router};
async fn health_check() -> &'static str {
    "OK"
}
async fn home() -> &'static str {
    "Home page"
}
async fn metrics() -> &'static str {
    "Metrics data"
}
fn health_routes() -> Router {
    Router::new()
        .route("/health", get(health_check))
        .route("/metrics", get(metrics))
}
fn home_routes() -> Router {
    Router::new()
        .route("/", get(home))
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .merge(health_routes())
        .merge(home_routes());
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Here health_routes() and home_routes() each return a complete Router with full paths. The .merge() calls combine them into a single route table. The final app Router matches /, /health, and /metrics.

The practical difference between nest and merge is straightforward. Use nest when you want a shared prefix. Use merge when each Router already contains its own full paths and you just need to combine them.

Conflicting Routes in Merge Panic:

If two Routers merged together both define the same path and method, merging panics - just as calling .route() twice with the same path and method panics. Merging two routers that each have their own fallback also panics, because a Router allows only a single fallback. Avoid defining the same route in multiple places when merging.

When No Route Matches

What happens when a request arrives for a path you did not define? Axum's Router has a built-in fallback. If no route matches the incoming method and path, the Router responds with 404 Not Found.

Here is a demonstration:

use axum::{routing::get, Router};
async fn home() -> &'static str {
    "Home page"
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

This server defines only GET /. If you visit http://localhost:3000/, you see "Home page". If you visit http://localhost:3000/nonexistent, Axum returns a 404 Not Found response with an empty body. If you send a POST request to /, the path matches but the method does not, so Axum returns a 405 Method Not Allowed response instead - with an Allow header naming the methods the path does support.

This default behavior is important to understand. The Router does not throw an error or crash when a request has no matching route. It handles the non-match gracefully and responds with the appropriate status code. Your application logic never runs for unmatched routes.

Customising the 405 Response

The default 405 response has an empty body. If you want a friendlier answer for matched-path-wrong-method requests, use Router::method_not_allowed_fallback. It sets a fallback handler that runs when a path is registered but the request's method is not:

use axum::{
    response::IntoResponse,
    routing::get,
    Router,
};

async fn home() -> &'static str {
    "Home page"
}

async fn handle_405() -> impl IntoResponse {
    (
        axum::http::StatusCode::METHOD_NOT_ALLOWED,
        "This path exists, but not for that method.",
    )
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home))
        .method_not_allowed_fallback(handle_405);
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Note the difference from Router::fallback, which runs only when no route matches at all (the 404 case). method_not_allowed_fallback applies only to previously registered routes, and only when the path matches but the method does not.

Knowing Which Route Matched: MatchedPath and OriginalUri

Two extractors are useful once routing gets more involved. MatchedPath gives you the route template that matched - /users/{user_id} rather than the concrete /users/42 - which is what you want for logging and metrics, so you do not create one label per user id:

use axum::{extract::MatchedPath, routing::get, Router};

async fn get_user(matched: MatchedPath) -> String {
    format!("Matched route template: {}", matched.as_str())
}

OriginalUri gives you the request URI as it arrived, before any nesting stripped a prefix. A nested router sees the URI with its matched prefix removed, which is what makes static-file serving under a prefix work - but if a nested handler needs the full original path, it extracts OriginalUri:

use axum::{extract::OriginalUri, http::Uri, routing::get, Router};

async fn show_uri(OriginalUri(uri): OriginalUri) -> String {
    format!("Original URI: {uri}")
}

Both are plain extractors: add them as handler arguments and Axum fills them in from the matched request.

Routing Mistakes That Cost Beginners Time

Several specific mistakes show up repeatedly when people first learn Axum routing.

Forgetting the #[tokio::main] Attribute

Every Axum application needs the #[tokio::main] attribute on main because Axum runs on Tokio's async runtime. Removing the attribute produces a compile error because the .await calls require an async context.

Missing tokio Attribute Stops Compilation:

Without #[tokio::main], the .await calls in main will fail to compile. The error message mentions something about needing an async context. The fix is always to add #[tokio::main] above the main function.

Using the Old Path Parameter Syntax

If you are reading older Axum tutorials, you might see routes like /users/:id. In Axum 0.7 and earlier, that was the correct syntax. In Axum 0.8 and later, the colon syntax no longer works - registering such a route panics at startup unless you first call Router::without_v07_checks(). Use {id} instead. Copying old code verbatim will crash the server at startup, not silently fail to match.

Mixing Up nest and merge

Both methods combine Routers, but they behave differently. nest adds a prefix to the nested Router's paths. merge does not add any prefix - it simply combines route tables. Using nest when you meant merge results in all your routes getting an unwanted prefix. Using merge when you meant nest means the nested Router's relative paths like / will conflict with the parent's root route.

Declaring Routes After the Server Starts

The Router is built before axum::serve() is called. Once the Router is handed to serve, you cannot add more routes to it. Any .route() calls must happen during the construction phase. If you try to modify the Router after serving has begun, the compiler will stop you because the Router is consumed by serve.

Forgetting That Method Matters

A route defined with get(home) only matches GET requests. A POST request to the same path will not match and will receive 405 Method Not Allowed (the path matched, the method did not). This surprises beginners who expect the path alone to determine the match. Axum matches on both method and path. You must define separate method handlers for the methods you want to support.

What Routing Sets Up for the Rest of Axum

Routing is the entry point to everything else Axum does. Once the Router matches a request to a handler, the handler can use extractors to pull data from the request, return various response types, access shared application state, and connect to middleware. But none of that happens until routing does its job.

The Router is also where middleware is attached. In Axum, middleware is applied using .layer() and .route_layer() calls on the Router, which wrap the matched handler in additional behavior. The routing layer determines which handler gets wrapped, and the middleware layer determines what happens around the handler's execution.

Understanding routing deeply means understanding that the Router is not just a simple path matcher. It is a composable, type-safe structure that integrates with the Tower ecosystem of services and layers. But the fundamental concept remains simple: you declare a set of patterns, Axum matches incoming requests against those patterns, and the right function runs - and all of those handler concepts assume you already know how the request got to the handler in the first place, which is exactly what routing accomplishes.

Routing Fundamentals Are Now In Place:

If you can explain what the Router does, how .route() adds entries, how path parameters and wildcards work, and the difference between nest and merge, you have mastered the routing layer. Every Axum application you build from this point forward will start with the same building blocks shown on this page.