Routing Basics
7 min read
Welcome to the Routing Basics module of the Actix Web course. 🦀
In the previous modules, you set up your environment and ran a "Hello World" application. Now, we must organize the chaos. An application without routing is like a library where all the books are piled in the center of the room—technically, the information is there, but good luck finding it.
Routing is the mechanism that maps an incoming HTTP request (a specific URL and method) to a specific piece of code (a handler) that processes it. It is the traffic controller of your web application.
Prerequisites 📦
Before we begin, ensure your Cargo.toml includes the necessary dependencies. We will be using serde for deserializing parameters, which is the industry standard in the Rust ecosystem.
[dependencies]
actix-web = "4"
serde = { version = "1.0", features = ["derive"] }1. Defining Routes and HTTP Methods 🛣️
Definition
A Route in Actix Web consists of a standard HTTP method (GET, POST, PUT, DELETE, etc.) and a URL pattern (path). A Handler is an asynchronous function that accepts request information and returns a response.
The Problem
Imagine you are building a blog API. You have an endpoint /posts. However, a user might want to read posts, create a new post, or delete all posts. If we only looked at the URL /posts, we would not know the user's intent.
The Solution
We utilize HTTP Verbs (Methods) to distinguish intent on the same resource path. Actix Web provides strict, type-safe macros to define these easily.
Implementation
Actix Web offers two primary ways to define routes: using attribute macros (preferred for readability) or manual configuration.
Method A: Attribute Macros (Recommended)
This method places the routing logic directly above the function definition.
use actix_web::{get, post, delete, HttpResponse, Responder};
// 1. Define the Handler
// This function handles GET requests to "https://localhost:8080/hello"
#[get("/hello")]
async fn hello() -> impl Responder {
HttpResponse::Ok().body("Hello there!")
}
// This function handles POST requests to "https://localhost:8080/echo"
#[post("/echo")]
async fn echo(req_body: String) -> impl Responder {
HttpResponse::Ok().body(req_body)
}
// 2. Register in App
// You must register these services in the main function.
/*
App::new()
.service(hello)
.service(echo)
*/Method B: Manual Route Configuration
Sometimes macros are too rigid for dynamic scenarios. You can define routes manually within the App builder using web::resource.
use actix_web::{web, HttpResponse};
async fn manual_hello() -> HttpResponse {
HttpResponse::Ok().body("Manual Hello!")
}
// Usage in App::new():
// App::new().service(
// web::resource("/manual")
// .route(web::get().to(manual_hello))
// )Interesting Fact: In the early days of the web, almost everything was a GET request. Forms were often hacked together. Today, adhering to RESTful standards (using GET for retrieving, POST for creating, etc.) is considered basic hygiene for your API.
2. Using Path Parameters (Dynamic URLs) 🆔
Definition
Path Parameters are variable segments within a URL path. They act as identifiers for specific resources.
The Problem
You are building a user profile system. You have users with IDs 1, 2, 3, and so on. It is computationally impossible to write a separate function for every single user ID (/users/1, /users/2, /users/3...).
The Solution
We use Dynamic Segments in the route definition and Extractors in the handler signature. Actix Web automatically extracts the value from the URL and parses it into the data type you specify.
Implementation
We use the syntax {name} inside the path to denote a variable. We use web::Path<T> to extract it.
use actix_web::{get, web, Responder};
// Define the route with a dynamic segment {user_id}
// The function argument must match the type you expect (u32 here).
#[get("/users/{user_id}")]
async fn get_user(path: web::Path<u32>) -> impl Responder {
let user_id = path.into_inner(); // Extract the inner u32
format!("Requesting details for User ID: {}", user_id)
}
// You can also extract multiple parameters
// URL: /users/5/friend/10
#[get("/users/{user_id}/friend/{friend_id}")]
async fn get_friend(path: web::Path<(u32, u32)>) -> impl Responder {
let (user_id, friend_id) = path.into_inner();
format!("User {} is friends with User {}", user_id, friend_id)
}Note on Type Safety: If a user visits /users/abc, Actix Web will automatically return a 400 Bad Request or 404 Not Found because "abc" cannot be parsed into a u32. You do not need to write regex validation for basic types manually.
3. Extracting Query Parameters 🔍
Definition
Query Parameters are key-value pairs that appear after the ? in a URL (e.g., /search?q=rust&sort=date). They are typically used for filtering, sorting, or pagination.
The Problem
You have an endpoint returning a list of products. A user wants to see only items that cost less than $50, sorted by name. Modifying the path structure for every filter combination (e.g., /products/cheap/sorted_by_name) is unscalable and violates REST principles.
The Solution
Use the web::Query<T> extractor. To handle this cleanly in Rust, we define a struct that represents the expected parameters and derive Deserialize from the serde crate.
Implementation
use actix_web::{get, web, Responder};
use serde::Deserialize;
// 1. Define the structure of your query parameters
#[derive(Deserialize)]
struct SearchParams {
keyword: String,
page: Option<u32>, // Optional parameter
}
// 2. Add web::Query<SearchParams> to function arguments
// URL Example: /search?keyword=actix&page=2
#[get("/search")]
async fn search(info: web::Query<SearchParams>) -> impl Responder {
let page = info.page.unwrap_or(1); // Default to page 1 if missing
format!("Searching for '{}' on page {}", info.keyword, page)
}If the user omits the keyword (which is not Option), the framework will reject the request. This enforces strict contract validation at the framework level.
4. Organizing Routes with Scopes and Service Configuration 📂
Definition
Scopes allow you to prefix a group of routes with a common path. Service Configuration allows you to move routing logic out of the main file and into modules.
The Problem
As your application grows, your main.rs file can become a "God Object"—a massive, unreadable file containing hundreds of routes. If you have an API with user routes, product routes, and admin routes, keeping them all in one list is a maintenance nightmare.
The Solution
- Scopes: Group routes under prefixes like
/api,/users, or/admin. - Configuration: Split code into different files/modules.
Implementation
Using Scopes
Scopes create a "sandbox" for routes.
use actix_web::{web, App, HttpServer, Responder, HttpResponse};
async fn index() -> impl Responder { "Hello World" }
async fn get_users() -> impl Responder { "User List" }
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(
// All routes inside here will be prefixed with /app
web::scope("/app")
.route("/index.html", web::get().to(index))
)
.service(
// All routes inside here will be prefixed with /api
web::scope("/api")
.route("/users", web::get().to(get_users))
)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}- Resulting URLs:
http://localhost:8080/app/index.htmlhttp://localhost:8080/api/users
Service Configuration (Modularization)
This is the industry standard for large Actix applications.
File: src/users.rs
use actix_web::{web, HttpResponse};
async fn get_all() -> HttpResponse { HttpResponse::Ok().body("All Users") }
async fn get_one() -> HttpResponse { HttpResponse::Ok().body("One User") }
// This function holds the configuration for this module
pub fn scoped_config(cfg: &mut web::ServiceConfig) {
cfg.service(
web::resource("/")
.route(web::get().to(get_all))
);
cfg.service(
web::resource("/{id}")
.route(web::get().to(get_one))
);
}File: src/main.rs
mod users; // Import the module
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(
// Mount the configuration under /api/users
web::scope("/api/users")
.configure(users::scoped_config)
)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}Imagination Check: Think of
Scopeslike folders in your computer's file system. You don't dump all your photos, documents, and music onto the Desktop. You create folders. Scopes are folders for your URL endpoints.
Summary ✅
In this module, we have transitioned from a simple "Hello World" to a structured routing system.
- We defined Routes using attributes like
#[get("/")]to map URLs to code. - We handled Dynamic URLs using
web::Pathto capture IDs. - We filtered data using Query Parameters with
web::Queryand Serde structs. - We organized our code using Scopes to prevent chaos in our main file.
Your application is now capable of understanding complex user requests. In the next module, we will explore "State Management"—how to share database connections and data across these routes.
References & Further Reading 📚
Challenge
Challenge: Build a Structured Product API
Your task is to create a complete Actix Web application structure within a single file. This application will manage a fictional product catalog and must adhere to modern API design practices by correctly organizing routes.
Requirements:
Serde Dependency: Assume
serdewith thederivefeature is available. You will need to use itsDeserializemacro.API Structure:
- Create a main API scope at
/api/v1. - All product-related endpoints must be modularized into a separate configuration function.
- This product configuration must be mounted under the
/productspath, resulting in a final base path of/api/v1/productsfor all product routes.
- Create a main API scope at
Query Parameters:
- Define a struct named
ProductFilterthat can be used to deserialize query parameters. - It should contain two optional fields:
categoryof typeStringandin_stockof typebool.
- Define a struct named
Handlers and Routes:
Implement the following three handler functions using attribute-based routing macros.
list_products:- Route:
GET /api/v1/products - Functionality: Accepts the
ProductFilterquery parameters. It should return a simple string confirming the request, for example:"Listing products with filters: category=electronics, in_stock=true". If a filter is not present, it should be omitted from the message.
- Route:
get_product:- Route:
GET /api/v1/products/{id} - Functionality: Extracts a dynamic
idfrom the path as au32. It should return a string confirming the ID, like"Fetching product with ID: 123".
- Route:
create_product:- Route:
POST /api/v1/products - Functionality: This route does not need to process a body. It should simply return a string confirming the action, like
"Creating a new product".
- Route:
Complete the main function to tie everything together and launch the HTTP server.
Expected result
Your final code should correctly implement a nested routing structure. The main function should initialize an App that creates a scope for /api/v1. Inside this scope, it should use .configure() to mount a dedicated product_config function under the /products path.
The product_config function should register the three required services: list_products, get_product, and create_product.
You must also define the ProductFilter struct with #[derive(Deserialize)] and implement the three handler functions with the correct attribute macros (#[get("/")], #[get("/{id}")], #[post("/")]) and extractor types (web::Query<ProductFilter>, web::Path<u32>).
use actix_web::{get, post, web, App, HttpServer, Responder, HttpResponse};
use serde::Deserialize;
#[derive(Deserialize)]
struct ProductFilter {
category: Option<String>,
in_stock: Option<bool>,
}
#[get("/")]
async fn list_products(filters: web::Query<ProductFilter>) -> impl Responder {
let mut response_text = String::from("Listing products");
if filters.category.is_some() || filters.in_stock.is_some() {
response_text.push_str(" with filters:");
}
if let Some(cat) = &filters.category {
response_text.push_str(&format!(" category={}", cat));
}
if let Some(stock) = &filters.in_stock {
response_text.push_str(&format!(", in_stock={}", stock));
}
HttpResponse::Ok().body(response_text)
}
#[get("/{id}")]
async fn get_product(path: web::Path<u32>) -> impl Responder {
let id = path.into_inner();
HttpResponse::Ok().body(format!("Fetching product with ID: {}", id))
}
#[post("/")]
async fn create_product() -> impl Responder {
HttpResponse::Ok().body("Creating a new product")
}
fn product_config(cfg: &mut web::ServiceConfig) {
cfg.service(list_products)
.service(get_product)
.service(create_product);
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(
web::scope("/api/v1")
.service(web::scope("/products").configure(product_config))
)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}