Routing: Directing Traffic
7 min read
Welcome to the Control Tower 🦀
Welcome back! If you are here, you likely have a basic Axum "Hello World" running. That’s great, but a web server that only says "Hello" is about as useful as a chocolate teapot.
To build real applications, your server needs to handle different requests, understand dynamic data, and stay organized. In web development, this is called Routing.
The Definition:
Routing is the process of selecting a specific handler function to execute based on the incoming HTTP request's URL path (e.g., /users) and HTTP Method (e.g., GET).
Think of your Axum application as a massive office building. The Router is the receptionist at the front desk. When a request comes in, the receptionist looks at where it wants to go (the URL) and what it wants to do (the Method), and points it to the correct department (the Handler Function).
1. Basic Routes: HTTP Methods (GET, POST, PUT, DELETE)
The Problem
You have different actions you want to perform. You want to read a profile, create a post, or delete a comment. You cannot use the same door for everything. If you try to send data to a logic block designed to just read data, chaos ensues.
The Solution
HTTP Methods. These are the verbs of the web. In Axum, we explicitly chain these methods to our Router.
- GET: Retrieve data (Read).
- POST: Submit data (Create).
- PUT/PATCH: Update data.
- DELETE: Remove data.
🛠️ Industry Practice
Axum makes this incredibly type-safe. You use helper functions like .route() combined with method handlers like get() or post().
Step 0: Dependencies
Make sure your Cargo.toml has the essentials. We need serde for the later steps, so let's add it now.
[dependencies]
axum = "0.7"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }Step 1: The Code
use axum::{
routing::{get, post},
Router,
};
use tokio::net::TcpListener;
#[tokio::main]
async fn main() {
// We build a router and attach routes to specific paths
let app = Router::new()
.route("/", get(root_handler))
.route("/users", post(create_user_handler));
let listener = TcpListener::bind("0.0.0.0:3000").await.unwrap();
println!("🚀 Listening on port 3000");
axum::serve(listener, app).await.unwrap();
}
// Handler for GET /
async fn root_handler() -> &'static str {
"Welcome to the API!"
}
// Handler for POST /users
async fn create_user_handler() -> &'static str {
// In real life, we'd read the body here.
"User created successfully"
}🧠 Under the Hood
When a request hits 0.0.0.0:3000/users with a POST method, Axum's internal tree traversal finds the match. If you send a GET request to /users, Axum automatically returns a 405 Method Not Allowed. You don't have to write logic to handle wrong methods; the framework protects you.
Fun Fact: Axum is built on top of
hyperandtower. It treats every handler as a "Service". This architecture allows Axum to handle thousands of concurrent requests without breaking a sweat, making it one of the fastest web frameworks on Earth.
2. Path Parameters: Capturing Variables from the URL
The Problem
Imagine you are building a profile page for a user. You have users with IDs 1, 2, 3... up to a million.
You obviously cannot write a route for every user:.route("/users/1", ...).route("/users/2", ...)
That is madness.
The Solution
Path Parameters. We use a placeholder in the URL (denoted by a colon :) to tell Axum, "Expect some data here, and capture it."
🛠️ Industry Practice
We use the axum::extract::Path extractor. Axum attempts to parse the URL segment into the Rust type you specify (e.g., i32, String, Uuid).
use axum::extract::Path;
// Route definition: Note the ":id" syntax
// .route("/users/:id", get(get_user_handler))
async fn get_user_handler(Path(user_id): Path<u32>) -> String {
format!("Requested profile for User ID: {}", user_id)
}Multiple Parameters
You can capture multiple segments easily.GET /teams/rust/members/42
// .route("/teams/:team_id/members/:member_id", get(team_member_handler))
async fn team_member_handler(
Path((team_id, member_id)): Path<(String, u32)>
) -> String {
format!("Team: {}, Member: {}", team_id, member_id)
}Warning ⚠️: If the user visits
/users/abcbut your handler expectsPath<u32>, Axum will reject the request with a 400 Bad Request before your function even runs. This is "Parse, don't validate" in action—if the types don't match, the handler is never called.
3. Query Parameters: Handling Search Strings
The Problem
Path parameters are great for identifying a specific resource, but what if you want to filter or sort data?
Example: GET /products?search=laptop&sort=price_asc.
These are optional modifiers. You shouldn't put them in the URL path structure because the resource is still "products".
The Solution
Query Parameters. These appear after the ? in the URL. Axum uses the Query extractor to automatically map these parameters into a Rust struct.
🛠️ Industry Practice
This is where serde shines. We define a struct that represents our search options.
use axum::extract::Query;
use serde::Deserialize;
// 1. Define the structure of your query params
// We use Option for fields that might be missing!
#[derive(Deserialize)] // Required to unpack data
struct SearchParams {
search: Option<String>,
page: Option<u32>,
}
// 2. The Handler
// URL Example: /products?search=shoes&page=2
async fn search_products(Query(params): Query<SearchParams>) -> String {
let search_term = params.search.unwrap_or_else(|| "all".to_string());
let page_num = params.page.unwrap_or(1);
format!("Searching for: {} on page {}", search_term, page_num)
}
// Router registration:
// .route("/products", get(search_products))🧠 What's happening?
When the request arrives, Axum looks at the query string. It uses serde to deserialize the string search=shoes&page=2 into your SearchParams struct. If the deserialization fails (e.g., someone types page=two instead of a number), Axum returns a 400 error.
Imagination Time: Query parameters are like the sticky notes attached to a file folder. The folder (Path) is the main object, but the sticky note (Query) tells you "Read this backwards" or "Only read the first page."
4. Nesting Routes: Organizing APIs
The Problem
In a real company, your main.rs file will quickly grow to 5,000 lines if you keep adding .route(). You might have routes for Users, Admin, Products, and Billing.
Also, you don't want to type /api/v1/users, /api/v1/products, /api/v1/billing over and over again.
The Solution
Nesting. You can create multiple Router instances and merge them or nest them inside each other. This allows you to split your code into different modules or files.
🛠️ Industry Practice
Group your logic by domain (Users, Products, etc.).
// Imagine this is in a separate module or file
fn user_routes() -> Router {
Router::new()
.route("/", get(get_all_users)) // Matches /api/users/
.route("/:id", get(get_user_by_id)) // Matches /api/users/:id
}
fn product_routes() -> Router {
Router::new()
.route("/", get(get_all_products))
}
#[tokio::main]
async fn main() {
// The "Child" router
let api_routes = Router::new()
.nest("/users", user_routes()) // Everything inside user_routes gets /users prefix
.nest("/products", product_routes());
// The "Parent" router
let app = Router::new()
.nest("/api", api_routes); // Everything inside api_routes gets /api prefix
// Resulting Routes:
// GET /api/users/
// GET /api/users/:id
// GET /api/products/
let listener = TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
// Dummy handlers
async fn get_all_users() -> &'static str { "All users" }
async fn get_user_by_id() -> &'static str { "One user" }
async fn get_all_products() -> &'static str { "All products" }Why do this?
- Readability: New developers can find "User" logic in the "User" module.
- Middleware Scoping: You can apply middleware (like authentication) only to the
/adminnested router, while leaving the/publicrouter open to everyone. (We will cover Middleware in a future lesson!).
Summary 📝
You've just upgraded from a basic "Hello World" to a structured API capable of handling traffic like a pro.
- Methods: Use
.route("/", get(handler))to map verbs to logic. - Path Params: Use
Path<T>and:idsyntax for dynamic resource IDs. - Query Params: Use
Query<Struct>for optional filtering and sorting. - Nesting: Use
.nest()to keep your code modular and clean.
Fact Check:
Did you know that axum::extract::Path and axum::extract::Query consume the request body parts they need? In Axum, the order of extractors in your function arguments matters! However, Path and Query extract from the URL headers, so they don't consume the body stream. You can usually place them anywhere in the argument list, but standard practice is Path first, then Query, then Json/Body.
📚 References & Further Reading
Challenge
Answer the following questions about the null value in programming within the provided comments in the code editor.
Expected result
Your response should include four distinct parts:
- A clear explanation that
nullrepresents the intentional and explicit absence of an object value. - A description of the difference, highlighting that
nullis an assigned value (the variable is defined but has no value), whereasundefinedtypically means a variable has been declared but has not been assigned a value. - A correct JavaScript variable assignment:
let userSelection = null;. - An explanation that assigning
nullmakes the program's intent clear—that the variable is meant to be empty at this point, which can make debugging and understanding the code's state easier.