Method Routers in Axum
Learn how to use method routers to handle different HTTP methods like GET, POST, PUT, and DELETE in your Axum application.
When you build a web server, every incoming request has an HTTP method attached to it. The method tells the server what the client wants to do: GET means "give me data", POST means "create new data", DELETE means "remove data", and so on. Axum's method routers are the tools you use to decide which piece of your code should run for each method on a given path.
What a Method Router Does
Think of your Axum application as a building with many rooms, each room responsible for a specific job. A request arrives at the front door with a sign that says "GET /users" or "POST /users". The router reads that sign and directs the request to the correct room. A method router is like a signpost that says "for GET requests on this path, go to this handler; for POST requests, go to that handler". It bundles a handler together with the HTTP method it should respond to.
In Axum, when you call route("/some/path", method_router), the second argument is always a MethodRouter. You rarely create a MethodRouter directly. Instead, you use helper functions like get, post, put, patch, delete, and any, which wrap your handler function and produce a MethodRouter configured for a specific HTTP method.
Let's start with the simplest possible example: a route that only responds to GET requests.
A Basic GET Route
use axum::{
routing::get,
Router,
};
async fn hello() -> &'static str {
"Hello, world!"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(hello));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
In this code, we import get from axum::routing. The get function takes our async handler hello and returns a MethodRouter that only accepts GET requests. We pass that to the route method on the / path. If you run this server and open http://127.0.0.1:3000/ in a browser, you'll see "Hello, world!" because browsers send GET requests by default.
Now try sending a POST request to the same address using curl:
curl -X POST http://127.0.0.1:3000/
You'll get back a response with status 405 Method Not Allowed. Axum automatically knows that this path exists, but only GET is allowed, so it rejects other methods. That's the core job of a method router.
Method Router Working Correctly:
If you see 405 Method Not Allowed after sending a POST to a GET-only route, that's not a bug. It's Axum telling you the method router did its job.
Handling Multiple Methods on One Path
Real APIs often need to handle different methods on the same URL. For example, /users might need GET to list users and POST to create a new user. Axum gives you two clean ways to do this.
Chaining Method Routers
The first way is to chain method router calls inside a single route call. Each helper function returns a MethodRouter, and that type has methods named after HTTP verbs that let you attach additional handlers for other methods.
use axum::{
routing::get,
Router,
};
async fn list_users() -> &'static str {
"List of users"
}
async fn create_user() -> &'static str {
"User created"
}
#[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();
}
Here, get(list_users) returns a MethodRouter that handles GET. We immediately call .post(create_user) on it, which returns a new MethodRouter that handles both GET and POST. The chain can continue with .put, .patch, .delete, and others.
Separate route Calls
You can also register the same path multiple times, each time with a different method router:
use axum::{
routing::{get, post},
Router,
};
async fn list_users() -> &'static str {
"List of users"
}
async fn create_user() -> &'static str {
"User created"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users", get(list_users))
.route("/users", post(create_user));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Both approaches produce the same result: GET /users goes to list_users, POST /users goes to create_user. The chained version is shorter and often preferred when you have several methods on the same path. The separate route calls can be useful when you are building routes in different parts of your code and want to keep them independent.
Do Not Register the Same Method Twice:
If you accidentally add two handlers for the same path and same HTTP method, Axum will panic when you build the router. For example, calling .route("/users", get(handler_a)).route("/users", get(handler_b)) is invalid. Keep one GET handler per path.
The MethodRouter Type and Chaining
Let's look more closely at what these helper functions return. When you write get(handler), you get a value of type MethodRouter. This type is not often named directly in beginner code, but it's important to understand that it's a builder. You can chain method calls on it to add more HTTP methods.
Here are the chaining methods you'll use most:
.get(handler)- handles GET requests.post(handler)- handles POST requests.put(handler)- handles PUT requests.patch(handler)- handles PATCH requests.delete(handler)- handles DELETE requests.on(method_filter, handler)- handles a custom set of methods
There is no .any(handler) chain method on MethodRouter. To accept every method, use the standalone any(handler) function from axum::routing instead, which creates a MethodRouter that matches all methods: .route("/health", any(health_check)).
Each of these methods returns a new MethodRouter that includes all previously added methods plus the new one. The order in which you chain doesn't matter, as long as you don't add the same method twice for the same path.
A Full REST Example
A common pattern is to build a REST API where a resource supports all CRUD operations. Let's create routes for a simple todo list. We'll keep handlers returning plain strings for now, but in a real app you'd return JSON.
use axum::{
routing::{get, post, put, patch, delete},
Router,
};
async fn list_todos() -> &'static str {
"List all todos"
}
async fn create_todo() -> &'static str {
"Create a todo"
}
async fn show_todo() -> &'static str {
"Show one todo"
}
async fn update_todo() -> &'static str {
"Replace a todo (PUT)"
}
async fn partial_update_todo() -> &'static str {
"Partially update a todo (PATCH)"
}
async fn delete_todo() -> &'static str {
"Delete a todo"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/todos", get(list_todos).post(create_todo))
.route(
"/todos/{id}",
get(show_todo)
.put(update_todo)
.patch(partial_update_todo)
.delete(delete_todo),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
In this example, /todos handles GET and POST, while /todos/{id} handles four different methods. The path parameter {id} will be available to the handlers that need it, but we've kept the handler signatures simple. If you run this server, you can test each method using curl:
curl http://127.0.0.1:3000/todos
curl -X POST http://127.0.0.1:3000/todos
curl http://127.0.0.1:3000/todos/42
curl -X PUT http://127.0.0.1:3000/todos/42
curl -X PATCH http://127.0.0.1:3000/todos/42
curl -X DELETE http://127.0.0.1:3000/todos/42
Each command will be routed to the correct handler based on the method and path.
Handling All Methods with any
Sometimes you have a route that should respond the same way no matter what HTTP method is used. A health check endpoint is a classic example: you don't care if it's GET, POST, or something else; you just want to return "OK". Axum provides the any helper for this.
use axum::{
routing::any,
Router,
};
async fn health_check() -> &'static str {
"OK"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/health", any(health_check));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Now GET /health, POST /health, DELETE /health, and any other method will all call health_check and return "OK". This is convenient, but be careful: if you later want to handle methods differently on that path, you'll need to remove any and use specific method routers. Also, any can hide bugs where a client sends an unexpected method - you won't get a 405 because the route will happily accept it.
HEAD Requests Are Handled Automatically:
When you register a route with get, Axum automatically also handles HEAD requests for that route. HEAD is like GET but without a response body. You don't need to add .head() explicitly.
How 405 Method Not Allowed Works
When a request comes in, Axum first tries to match the path against all registered routes. If it finds a path that matches, it then checks whether the request's HTTP method is allowed by the method router attached to that path. If the method is not allowed, Axum returns a 405 Method Not Allowed response and includes an Allow header listing the methods that are permitted.
This is automatic and requires no code from you. It's a useful behavior for clients because they can discover what operations are supported on a resource. For example, if you send a PUT to /todos in the earlier REST example, you'll get:
HTTP/1.1 405 Method Not Allowed
allow: GET, POST
The allow header tells you that GET and POST are valid. This is part of the HTTP specification and Axum implements it correctly out of the box.
Method Routers with Path Parameters
We saw earlier that you can use path parameters like {id} together with method routers. The parameter is available to your handler via the Path extractor. Let's expand the todo example to actually use the id in the handler responses.
use axum::{
extract::Path,
routing::{get, post, put, delete},
Router,
};
async fn list_todos() -> String {
format!("List all todos")
}
async fn create_todo() -> String {
format!("Create a todo")
}
async fn show_todo(Path(id): Path<u64>) -> String {
format!("Show todo with id {}", id)
}
async fn update_todo(Path(id): Path<u64>) -> String {
format!("Replace todo with id {}", id)
}
async fn delete_todo(Path(id): Path<u64>) -> String {
format!("Delete todo with id {}", id)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/todos", get(list_todos).post(create_todo))
.route(
"/todos/{id}",
get(show_todo)
.put(update_todo)
.delete(delete_todo),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Now GET /todos/42 will call show_todo with id equal to 42, and the response will be "Show todo with id 42". Similarly for PUT and DELETE. The Path extractor automatically parses the id segment as a u64; if the segment isn't a valid number, Axum will return a 400 Bad Request before your handler runs.
Path Parameter Type Must Match:
If you declare Path(id): Path<u64> but the URL contains a non-numeric value like /todos/abc, Axum will reject the request with a 400 error. Make sure your parameter types align with the data you expect.
Mixing Static and Dynamic Paths
A common question is whether you can have both /todos/new and /todos/{id}. Axum handles this well: static segments take precedence over dynamic ones. If a request comes in for /todos/new, it will match the static route before considering the dynamic {id} route.
Here's an example:
use axum::{
extract::Path,
routing::{get, post},
Router,
};
async fn new_todo() -> &'static str {
"Form for new todo"
}
async fn show_todo(Path(id): Path<u64>) -> String {
format!("Show todo with id {}", id)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/todos/new", get(new_todo))
.route("/todos/{id}", get(show_todo));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
When you visit /todos/new, it goes to new_todo, not show_todo. This is because Axum checks static routes first. This behavior lets you design URLs that are both human-friendly and flexible.
Common Mistakes and How to Avoid Them
Overlapping Routes
As mentioned earlier, adding two handlers for the same path and same method will cause Axum to panic. This is a runtime check, not a compile-time one: the panic happens immediately, when the second .route() call runs - while your program is building the router, long before axum::serve is called. The panic message will tell you which path and method conflict, for example Overlapping method route. Handler for \GET /foo` already exists`. For example, this code will panic:
let app = Router::new()
.route("/foo", get(handler_a))
.route("/foo", get(handler_b));
// `handler_a` and `handler_b` stand for any two async handler functions.
To fix it, either remove one of the routes or differentiate them by method. If you need different behavior based on something else, use a single handler with internal logic.
Forgetting to Import Helper Functions
Each HTTP method helper lives in axum::routing. You must import them explicitly. A common mistake is to write routing::get but forget to add use axum::routing::get; at the top. The compiler will remind you, but it's easy to overlook.
Not Understanding HEAD Handling
Since Axum automatically supports HEAD for GET routes, you might think you need to add a separate .head() method. You don't. However, if you need to customize HEAD behavior beyond returning the same headers without a body, you can use .on(MethodFilter::HEAD, handler) to give HEAD its own handler.
Using any When Specific Methods Are Needed
It's tempting to use any for convenience, but it can hide mistakes. If you expect only GET and POST but accidentally send a DELETE, any will accept it. It's often better to explicitly list the methods you support so that unsupported methods get a clear 405 response.
Using any Can Mask Errors:
Reserve any for cases where you genuinely want to accept all methods, like health checks or debugging endpoints. For normal resources, define specific methods.
Choosing Between Chaining and Separate route Calls
Both approaches are valid, and the choice often comes down to code organization.
- Chaining keeps all methods for a path in one place, which is easy to scan. It's ideal when a single resource has several operations that are closely related.
- Separate
routecalls can be useful when different parts of your application contribute handlers for the same path. For example, a plugin system might add a POST handler to an existing route without touching the original code.
You can also mix the two: register a GET handler with one route call and then later chain POST and PUT in another route call. The only rule is not to register the same method twice for the same path.
Putting It All Together: A Mini REST API
Let's build a small but complete REST API for managing books. We'll use method routers to handle all CRUD operations, and we'll include a simple in-memory store to make the responses slightly more realistic. Keep in mind that this example is still simplified; a production app would use a database.
We'll structure the code in a single file for clarity. The Book struct uses serde's derive macros, so Cargo.toml needs serde with the derive feature, plus serde_json for JSON support:
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
Here is the full program:
use axum::{
extract::Path,
response::IntoResponse,
routing::get,
Router,
http::StatusCode,
Json,
};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use serde::{Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize)]
struct Book {
id: u64,
title: String,
author: String,
}
type BookStore = Arc<Mutex<HashMap<u64, Book>>>;
async fn list_books(store: axum::extract::State<BookStore>) -> impl IntoResponse {
let store = store.lock().unwrap();
let books: Vec<Book> = store.values().cloned().collect();
Json(books)
}
async fn create_book(
axum::extract::State(store): axum::extract::State<BookStore>,
Json(book): Json<Book>,
) -> impl IntoResponse {
let mut store = store.lock().unwrap();
let id = book.id;
store.insert(id, book);
(StatusCode::CREATED, Json("Book created"))
}
async fn get_book(
Path(id): Path<u64>,
axum::extract::State(store): axum::extract::State<BookStore>,
) -> impl IntoResponse {
let store = store.lock().unwrap();
match store.get(&id) {
Some(book) => Json(book.clone()).into_response(),
None => (StatusCode::NOT_FOUND, "Book not found").into_response(),
}
}
async fn update_book(
Path(id): Path<u64>,
axum::extract::State(store): axum::extract::State<BookStore>,
Json(book): Json<Book>,
) -> impl IntoResponse {
let mut store = store.lock().unwrap();
if store.contains_key(&id) {
store.insert(id, book);
(StatusCode::OK, "Book updated").into_response()
} else {
(StatusCode::NOT_FOUND, "Book not found").into_response()
}
}
async fn delete_book(
Path(id): Path<u64>,
axum::extract::State(store): axum::extract::State<BookStore>,
) -> impl IntoResponse {
let mut store = store.lock().unwrap();
if store.remove(&id).is_some() {
(StatusCode::OK, "Book deleted").into_response()
} else {
(StatusCode::NOT_FOUND, "Book not found").into_response()
}
}
#[tokio::main]
async fn main() {
let store: BookStore = Arc::new(Mutex::new(HashMap::new()));
let app = Router::new()
.route(
"/books",
get(list_books).post(create_book),
)
.route(
"/books/{id}",
get(get_book)
.put(update_book)
.delete(delete_book),
)
.with_state(store);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
This example introduces a few new concepts like application state and JSON responses, but the routing part is exactly what we've been discussing. Notice how we chain get(list_books).post(create_book) for the collection path, and get(get_book).put(update_book).delete(delete_book) for the item path. We didn't include PATCH here for brevity, but you could easily add it.
Complete Routing Setup:
This mini API demonstrates how method routers form the backbone of a RESTful service. Each path handles the appropriate methods, and Axum automatically returns 405 for unsupported methods like PATCH on /books.
Summary
Method routers are the mechanism Axum uses to connect HTTP methods to your handler functions. You create them using helpers like get, post, put, patch, delete, and any, and you attach them to paths via the route method. By chaining these helpers or using multiple route calls, you can make a single URL respond differently depending on the HTTP method.
The key insight is that a route in Axum is not just a path; it's a combination of a path and a method filter. When a request arrives, Axum matches the path first, then checks if the method is allowed. If not, it returns a clean 405 with an Allow header. This behavior makes your API self-descriptive and helps clients understand what they can do.
Now that you understand method routers, you have the core building block for creating rich, RESTful APIs with Axum. The next natural step is to explore the individual helper functions in more depth, but you already know enough to build functional routes for almost any web service.