Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 38 ยท Routers and Handlers

Axum Routing Basics: Router, route and Methods

Learn how Axum routes requests: Router::new and route, method routers like get and post, chaining several methods on one path, any, and how 405 responses are produced.

Routing answers one question: given a method and a path, which function should run? In Axum the answer is a Router. You create one, add routes to it, and hand it to axum::serve. Each route pairs a path with a method router that says which handler serves which HTTP method.

This lesson covers the core API: Router::new, route, the method helpers (get, post, put, patch, delete, any), chaining methods on one path, and what Axum does when the path exists but the method does not. Path parameters, nesting and fallbacks have their own lessons next.

Router and route

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

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

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

fn app() -> Router {
    Router::new()
        .route("/", get(home))
        .route("/about", get(about))
}

Router::new() starts empty; every route call returns a new router with one more entry, so you chain them. The first argument is the path, which must start with /. The second is a MethodRouter, built by get(handler).

A router is just a value. You can build it in a function, pass it around, merge it with others and test it. Nothing listens on a port until you give it to axum::serve.

One path, several methods

REST-style APIs put several methods on the same path: GET /notes lists notes, POST /notes creates one. You chain method helpers:

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

async fn list_notes() -> &'static str { "all notes" }
async fn create_note() -> &'static str { "created" }
async fn show_note() -> &'static str { "one note" }
async fn remove_note() -> &'static str { "deleted" }

fn app() -> Router {
    Router::new()
        .route("/notes", get(list_notes).post(create_note))
        .route("/notes/{id}", get(show_note).delete(remove_note))
}

The helpers imported from axum::routing start a method router (get(list_notes)), and the same-named methods on a MethodRouter (.post(create_note)) add more. You can mix them: get(a).post(b).put(c).delete(d).patch(e).

Handlers for each method are independent functions; they can take different extractors and return different types. Calling .route("/notes", ...) twice for the same path is allowed as long as the methods do not overlap; two handlers for the same method and path make the router panic at start-up, which is what you want: the mistake appears immediately, not in production.

The method helpers

Helper Matches
get, post, put, patch, delete, head, options, trace That one method
any(handler) Every method
on(MethodFilter::GET.or(MethodFilter::POST), handler) A set of methods

get also answers HEAD requests automatically with the body removed, so you rarely need head yourself.

What happens when the method does not match

A request for DELETE /about when only GET /about is registered gets 405 Method Not Allowed with an Allow: GET,HEAD header, produced by Axum itself. A request for a path that no route matches gets 404 Not Found with an empty body. You can customise both; see fallbacks and 405 responses.

A runnable model of method routing

The model mirrors the structure: a router holds paths, each path holds a method router (a map from method to handler), and a miss on the path or the method produces 404 or 405 with an Allow header. The builder style (get(h).post(h2)) is the same as Axum's. Registering the same method and path twice panics, like the real router.

Rust Stand-in: Router, MethodRouter and 404/405

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Notice that DELETE /notes gets a 405 listing the allowed methods, while /missing is a plain 404: the router knows the difference between "no such place" and "no such action here".

The overlap rule

Axum's router is built when you write the code, not when requests arrive. Two cases fail immediately with a panic and a readable message:

  1. The same method registered twice for the same path.
  2. Two paths that would be ambiguous (for example /users/{id} and /users/{name}, which are the same shape with different names).

The next model shows the first case being caught, using std::panic::catch_unwind to print the message instead of crashing.

Rust Stand-in: overlapping routes fail at start-up

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Trailing slashes and path rules

  • Paths must start with /.
  • /notes and /notes/ are different routes. Axum does not redirect between them; pick one convention (usually no trailing slash) and keep to it. A tower-http layer can normalise paths if clients are sloppy.
  • Matching is exact apart from parameters and wildcards, which you meet in path parameters and wildcards.
  • Route order does not matter. Axum compiles routes into a radix tree, so a static path such as /users/me beats /users/{id} regardless of which you wrote first.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you serve GET and POST on /notes with different handlers?

    Chain method helpers on one MethodRouter: get(list).post(create).
  2. 2. A client sends DELETE to a path that only has GET. What does Axum return?

    The path exists but not for that method, so Axum answers 405 and lists the allowed methods.
  3. 3. What happens if you register the same method on the same path twice?

    Overlapping routes are rejected at start-up so the mistake cannot reach production.
  4. 4. Does the order in which you add routes affect which one matches?

    Routing is not order based; static segments beat parameters.

Summary

  • Router::new().route(path, method_router) builds a router; get(h).post(h2) chains methods on one path.
  • Paths that exist with the wrong method give 405 and an Allow header; unknown paths give 404.
  • Overlapping registrations panic at start-up.
  • /x and /x/ are different, and route order does not matter.

Next: Handler Functions