The route Method in Axum

Learn how to use the route method to map HTTP methods and paths to handler functions in Axum

When you build a web server with Axum, you need a way to tell the server what code to run for each incoming request. The route method on Router does exactly that. It takes a URL path and a method router - a value built by a helper like get that pairs one HTTP method with a handler function - then stores that rule in the router so that when a matching request arrives, the right handler runs.

What the route Method Does

Every HTTP request that reaches your server has two important pieces: an HTTP method (like GET, POST, PUT, DELETE) and a URL path (like /, /users, or /posts/42). A web framework needs a way to connect each combination of method and path to a piece of code that produces a response. That piece of code is called a handler.

In Axum, the route method is how you register that connection. You call it on a Router, and each call adds one routing rule. The method returns the same Router (well, a new value of the same type), so you can chain multiple route calls together in a single expression. This chain builds a routing table that Axum uses later when a real request arrives.

Building vs Serving:

The route method does not start any server or handle any requests on its own. It only records rules inside the Router. The actual request handling happens later, after you pass the router to axum::serve. Think of route as writing an instruction book, and serve as opening the restaurant.

Your First route Call

Let's start with the smallest possible example. Create a new Rust project (or use the one you already have) and write this complete src/main.rs file:

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

The line .route("/", get(root)) is the focus. It says: "For a GET request to the path /, run the root function." The get function comes from axum::routing and is a small wrapper that builds a MethodRouter that only accepts GET. The root function is our handler - it returns a string, which Axum automatically converts into an HTTP response with status 200 and a plain text body.

If you run this with cargo run and visit http://127.0.0.1:3000/ in a browser or with curl, you'll see Hello, world!.

If you see the greeting, your routing works:

The moment you get Hello, world! back from the server, you have successfully used route to connect a path and method to a handler. Everything else from here is variations on that same pattern.

The Two Arguments of route

The route method takes two arguments:

  1. A path string - a &str that describes which URL paths this rule applies to. It must start with a forward slash /. Examples: /, /about, /users, /posts/42.
  2. A method router - a value that says which HTTP method(s) this rule accepts and which handler to call for matching requests. The most common way to create this value is with a function like get, post, put, delete, or others from axum::routing.

The path string must always begin with /. If you forget the leading slash, Axum will panic (crash) when you try to build the router, with an error message telling you the path must start with /.

// This works
let app = Router::new().route("/", get(handler));
// This panics
// let app = Router::new().route("", get(handler));
// The error says: "Paths must start with a `/`"

The method router is built using a function named after the HTTP method you want. These functions are all exported from axum::routing. They take a handler and return a MethodRouter object. We'll explore them next.

Common HTTP Methods and Their Routing Helpers

Axum provides a routing helper for every standard HTTP method. You already saw get. The full list includes get, post, put, delete, patch, head, options, trace, connect, and any. Each one except any creates a MethodRouter that accepts exactly that method. The any helper is the exception: it accepts every method, so one any(handler) rule answers GET, POST, and anything else sent to that path.

Here is a small application with four different routes, each using a different method:

src/main.rs
use axum::{routing::{get, post, put, delete}, Router};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(index))
        .route("/users", post(create_user))
        .route("/users/42", put(update_user))
        .route("/users/42", delete(delete_user));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn index() -> &'static str {
    "Welcome to the home page"
}
async fn create_user() -> &'static str {
    "Creating a new user"
}
async fn update_user() -> &'static str {
    "Updating user 42"
}
async fn delete_user() -> &'static str {
    "Deleting user 42"
}

Each route call adds a separate rule. Notice that two different methods can be attached to the same path - /users/42 has both a PUT and a DELETE rule. The router knows how to tell them apart by the HTTP method of the incoming request.

This example uses fixed paths. In a real app, you'd want to handle many different user IDs, not just 42. Axum supports path parameters, which are part of the path string, but we'll cover those in detail when we talk about routing patterns. For now, just know that /users/42 is an exact match.

Chaining Multiple Methods on a Single Path

Often you want the same URL to respond to different HTTP methods with different handlers. For example, GET /users could list all users, while POST /users could create a new one. You could call route twice with the same path and different method routers, but Axum gives you a more compact way: chain the method routers on the same route call.

Look at how get, post, etc. each return a MethodRouter. That MethodRouter has its own methods named get, post, put, and so on, which you can chain to add more method handlers to the same path. The code reads left to right:

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

Here get(list_users) returns a MethodRouter that knows how to handle GET. Calling .post(create_user) on that MethodRouter adds a POST handler to the same rule. The whole expression .route("/users", get(list_users).post(create_user)) registers both methods at once.

You can chain as many methods as you need:

.route("/resource", get(read).post(create).put(update).delete(remove))

This is the preferred style when you have multiple methods on the same path because it keeps the routing table organized and avoids repeating the path string.

Registering Multiple Routes

The route method returns the Router itself, so you can continue chaining more route calls. This lets you build up a large routing table in one smooth expression:

src/main.rs
use axum::{routing::{get, post}, Router};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home))
        .route("/about", get(about))
        .route("/login", get(login_page).post(login_form))
        .route("/logout", post(logout));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn home() -> &'static str { "Home" }
async fn about() -> &'static str { "About us" }
async fn login_page() -> &'static str { "Login form" }
async fn login_form() -> &'static str { "Login submitted" }
async fn logout() -> &'static str { "Logged out" }

Each .route(...) call adds a new rule to the router. The order you write the calls in does not decide which rule wins: when two patterns could both match a request, the more specific one wins - an exact path like /users/new beats a parameter pattern like /users/{id} no matter which was registered first. Two rules that truly overlap for the same method and path are not resolved by order at all; the router refuses them and panics when it is built, as the duplicate-path mistake below shows.

Using Closures as Handlers

You don't always need a separate named function for every handler. Axum accepts async closures as well, as long as they return something that can become an HTTP response. This is handy for very simple handlers where defining a named function feels like overhead.

Here is an example that uses an inline closure:

src/main.rs
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(|| async { "Hello from a closure!" }))
        .route("/health", get(|| async { "OK" }));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

The closure is written as || async { ... }. The || means "no arguments", and async { ... } makes it an async block. The get function can accept any type that implements the Handler trait, and both named functions and async closures do.

Keep in mind that closures used as handlers must be Clone + Send + Sync + 'static, so they cannot borrow data from the surrounding function. For larger handlers a named function is usually clearer. But for quick prototypes, closures keep everything in one place.

Path Patterns and Exact Matching

So far, every path we used was an exact string like / or /users. Axum treats these as exact matches: the incoming request path must equal the string exactly, character for character. If the request comes to /Users with a capital U, it will not match /users. Paths are case-sensitive by default.

You can also use path parameters, which are placeholders that match any value in that segment. The syntax uses curly braces: {param}. For example:

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

Here /users/{id} matches /users/1, /users/abc, /users/anything, but not /users (because it requires the extra segment) and not /users/1/2 (because the path has three segments). The handler receives the captured value through the Path extractor. We will explore path parameters in their own dedicated page later, but it's useful to know that route supports them right in the path string.

Path parameters use curly braces, not colons:

In older versions of Axum (before 0.8), path parameters used a colon like :id. In Axum 0.8 and later, you must use curly braces: {id}. If you are following an old tutorial that shows :id, replace it with {id}.

Common Mistakes and How to Fix Them

Working with route is usually straightforward, but there are a few traps that catch beginners. Let's walk through the most common ones.

Forgetting the leading slash

The path string must start with /. If you write route("users", get(handler)) (without the leading slash), the program will panic with a message like Paths must start with a /``. Always check that your path begins with /.

Using the wrong method router

If you register a route with get(handler) but then send a POST request to that path, Axum will respond with 405 Method Not Allowed because no POST rule exists. The fix is either to send the correct method or to register that method as well, using chaining:

.route("/submit", get(show_form).post(handle_submit))

Duplicate exact paths with the same method

If you call route twice with the same exact path and the same method, your program will panic when the router is built. For example:

let app = Router::new()
    .route("/", get(first))
    .route("/", get(second));

Running this panics with a message like:

Overlapping method route. Handler for `GET /` already exists

Axum refuses to guess which handler you meant, so it stops the program instead of silently picking one. If you need both handlers to run for the same request, combine them into one handler.

Note that this panic only happens when the method is the same. Registering the same path with different methods - for example .route("/users", get(list)) followed by .route("/users", post(create)) - is perfectly fine: the two route calls merge into one rule that handles both methods.

Duplicate routes crash the server at startup:

Registering the same path with the same method twice is not a warning and not a silent overwrite - the program panics while the router is being built and never serves a single request. If your server exits immediately with an Overlapping method route message, look for two route calls with the same path and method and remove or merge one of them.

Confusing route with nest

The route method is for mapping a single path directly to a handler. Axum also has a nest method that lets you mount a whole sub-Router at a prefix. Don't mix them up: route expects a handler, nest expects another Router. This page only covers route.

How route Fits Into the Larger Picture

When you write Router::new().route("/", get(root)), you are doing two things:

  1. Creating an empty Router with Router::new().
  2. Adding a routing rule to it with .route(...).

The result is a value of type Router. This value is just a data structure - it holds a mapping from (method, path pattern) to handler. It does not do any network I/O by itself.

Later, when you pass this router to axum::serve, the server starts listening for incoming TCP connections. For each HTTP request, Axum looks at the method and path, searches the router's table for a matching rule, and if found, calls the corresponding handler. The response from the handler is then sent back to the client.

The route method is therefore the primary way you define what your application does. Every route you add is a promise: "When someone asks for this, I will do that." The more routes you add, the more capable your server becomes.

Router is immutable by design:

Every call to route returns a new Router with the additional rule added. It does not modify the original router. This is why you often see the whole chain assigned to a variable: let app = Router::new().route(...).route(...); The original Router::new() value is not used after that.

Summary

The route method is the core building block for defining HTTP endpoints in Axum. It maps a path and HTTP method to a handler function. You call it on a Router, and it returns the Router again so you can chain multiple calls. You can register different methods on the same path by chaining method routers like .get(...).post(...). The path string must start with / and can include path parameters using curly braces.

A complete minimal application looks like this:

src/main.rs
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(root))
        .route("/health", get(health));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
async fn root() -> &'static str {
    "Hello, world!"
}
async fn health() -> &'static str {
    "OK"
}

Once you can write and run this, you can register routes with confidence. The decision that matters most when you add a route is which shape it needs: one path with one method is a single route call, several methods on one path belong in one chained call so the path is written once, and a second handler for the same method and path is never the answer - the router stops your program rather than guess. Handlers are where the work happens, so what a handler can accept and return decides what a route can do.