One Handler File Per Resource
Learn how to organize Axum handler functions by creating one dedicated file for each resource such as users or products.
When an Axum application grows beyond a handful of endpoints, putting every handler function inside main.rs becomes painful. This page teaches a simple file organization pattern that keeps handlers easy to find, easy to maintain, and easy to extend: one file per resource.
Why Your main.rs Becomes a Mess
Imagine you are building an API that manages three things: users, todos, and products. Each of these "things" needs five operations: list all records, get one record, create a record, update a record, and delete a record. That is already fifteen handler functions if you include all five standard operations for each resource.
If you write all fifteen functions inside main.rs, here is what the start of that file looks like:
// src/main.rs - DO NOT ORGANIZE YOUR PROJECT THIS WAY
use axum::{Router, routing::{get, post, put, delete}};
async fn list_users() -> &'static str {
"all users"
}
async fn get_user() -> &'static str {
"one user"
}
async fn create_user() -> &'static str {
"user created"
}
async fn update_user() -> &'static str {
"user updated"
}
async fn delete_user() -> &'static str {
"user deleted"
}
async fn list_todos() -> &'static str {
"all todos"
}
async fn get_todo() -> &'static str {
"one todo"
}
async fn create_todo() -> &'static str {
"todo created"
}
// ... many more handlers below ...
The problem is not the code itself. The problem is that every handler for every resource lives in the same physical space. As you scroll through the file, the context switches constantly: user handlers, todo handlers, product handlers, user handlers again. When you need to change how deleting a todo works, you have to hunt through a wall of unrelated user and product functions to find the one function you care about.
This is not a theoretical concern. Real Rust backends routinely grow to hundreds of handler functions. A single file with hundreds of unrelated functions is exhausting to navigate. When two developers work on different resources at the same time, they both edit the same file and create merge conflicts that never needed to happen.
The Core Idea:
The one-file-per-resource pattern exists because files are the cheapest way to group related code. When all user handlers live in one file and all todo handlers live in another, the file name itself tells you exactly where to look.
What Is a Resource
Before setting up the file structure, you need a working definition of the word "resource." In HTTP API design, a resource is a type of thing your application manages and exposes through routes. Users are a resource. Todos are a resource. Products, orders, comments, and blog posts are all resources.
Resources almost always follow a predictable shape. A users resource has routes for listing users, reading a single user, creating a user, updating a user, and deleting a user. A todos resource has the same five operations, just targeting todos instead of users. This repetition is useful because it means the organization pattern you learn once applies to every resource you ever build.
When you see an API route like GET /users/{id}, the word "users" tells you which resource is being accessed. The same logic applies to file names. A file called users.rs in a handlers directory tells you - without opening the file - that every handler inside it deals with the users resource.
The One File Per Resource Pattern
The pattern is simple: create a directory called handlers inside src. Inside that directory, create one Rust file for each resource your API serves. The file name matches the resource name.
Here is what a project with three resources looks like:
src/
main.rs
handlers/
mod.rs
users.rs
todos.rs
products.rs
users.rs contains every handler that operates on the users resource. todos.rs contains every handler for todos. products.rs contains every handler for products. The mod.rs file exists to declare these files as Rust modules so the rest of the project can use them.
A beginner-friendly way to think about this: the handlers directory is a filing cabinet, and each resource file is a labeled folder inside it. When you need to fix the "create todo" handler, you open the todos.rs folder. You never have to open the users folder by accident.
This pattern does not require any special library or framework feature. It is plain Rust module organization applied to Axum handlers. Axum does not care where your handler functions live - it only cares that they exist and are accessible when you build your Router. The organization is entirely for you and your teammates.
Step-by-Step: Setting Up handlers/users.rs
The first time you organize handlers into files, the Rust module system can feel confusing. Let's walk through it as a sequence of concrete steps.
Before the steps, make sure your project has the dependencies the examples on this page use. axum is the web framework, tokio runs the async server, and serde_json is needed later for the example that returns JSON. Add them to your Cargo.toml:
# Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde_json = "1"
A dependency is a crate your project uses from the Rust package registry. axum = "0.8" means any version starting with 0.8, which includes 0.8.9. The full feature on tokio switches on everything tokio offers, so you do not have to pick individual features while learning.
Step 1: Create the handlers directory
Inside your project's src directory, create a new directory named handlers. If your project root is the folder containing Cargo.toml, the full path is src/handlers.
your-project/
Cargo.toml
src/
main.rs
handlers/ <- create this directory
At this point the directory is empty. Rust does not know it exists yet.
Step 2: Create mod.rs inside handlers
The classic layout for a directory module uses a file named mod.rs inside the directory - this is the layout this page uses. (Since Rust 2018, a newer layout also works: a handlers.rs file next to a handlers/ directory. Either layout works, but you must use one of them; mod.rs is the traditional choice.) This file is the entry point for the module. Create src/handlers/mod.rs and leave it empty for now.
your-project/
Cargo.toml
src/
main.rs
handlers/
mod.rs <- create this file
Without a mod.rs file (or the newer handlers.rs alternative), Rust will not recognize handlers as a module, and nothing inside it will be accessible from main.rs.
Step 3: Create users.rs with handler functions
Create src/handlers/users.rs. This file will hold all five CRUD handlers for the users resource. For this first example, each handler returns a short string so you can focus on the file structure rather than handler internals.
// src/handlers/users.rs
// List all users
pub async fn list_users() -> &'static str {
"all users"
}
// Get one user by ID
pub async fn get_user() -> &'static str {
"one user"
}
// Create a new user
pub async fn create_user() -> &'static str {
"user created"
}
// Update an existing user
pub async fn update_user() -> &'static str {
"user updated"
}
// Delete an existing user
pub async fn delete_user() -> &'static str {
"user deleted"
}
Notice the pub keyword before every function. In Rust, functions inside a module are private by default. A private function cannot be called from main.rs or from any other module. If you omit pub, the router setup in main.rs will fail with a compile error saying the function is private.
Step 4: Declare the users module in mod.rs
Open src/handlers/mod.rs and add a single line that declares the users module as public.
// src/handlers/mod.rs
pub mod users;
This line tells Rust: "There is a file named users.rs in this directory. Make it available as a public module so other parts of the project can use it."
Step 5: Declare the handlers module in main.rs
Open src/main.rs and add mod handlers; near the top, before your fn main function.
// src/main.rs
mod handlers;
fn main() {
// router setup will go here
}
This line tells Rust: "There is a directory named handlers with a mod.rs inside it. Load that module."
Step 6: Wire the handlers into your Router
Now build your Router and point each route at the correct handler function. The path to each function uses the module name as a prefix: handlers::users::list_users.
// src/main.rs
mod handlers;
use axum::{Router, routing::get};
use handlers::users;
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users", get(users::list_users).post(users::create_user))
.route(
"/users/{id}",
get(users::get_user)
.put(users::update_user)
.delete(users::delete_user),
);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The use handlers::users; line imports the users module into the current scope. After that, you can write users::list_users instead of the longer handlers::users::list_users. Only the get routing function is imported, because .post, .put, and .delete are methods on the route itself, not free functions.
If you run cargo run at this point and open http://localhost:3000/users in a browser, you will see the text all users. That confirms the file organization is working correctly and the router is reaching the handler inside users.rs.
Working File Organization:
When your app compiles and routes resolve correctly, the module declaration chain is complete: main.rs declares handlers, handlers/mod.rs declares users, and users.rs exposes public functions. Seeing the expected response means every link in that chain is correct.
Adding a Second Resource
The real value of this pattern appears when you add a second resource. Instead of touching main.rs or users.rs, you create one new file and add one line to mod.rs.
Create src/handlers/todos.rs with the same five operations:
// src/handlers/todos.rs
pub async fn list_todos() -> &'static str {
"all todos"
}
pub async fn get_todo() -> &'static str {
"one todo"
}
pub async fn create_todo() -> &'static str {
"todo created"
}
pub async fn update_todo() -> &'static str {
"todo updated"
}
pub async fn delete_todo() -> &'static str {
"todo deleted"
}
Then update src/handlers/mod.rs to include the new module:
// src/handlers/mod.rs
pub mod todos;
pub mod users;
Finally, extend the router in src/main.rs to import and route the new handlers:
// src/main.rs
mod handlers;
use axum::{Router, routing::get};
use handlers::{todos, users};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users", get(users::list_users).post(users::create_user))
.route(
"/users/{id}",
get(users::get_user)
.put(users::update_user)
.delete(users::delete_user),
)
.route("/todos", get(todos::list_todos).post(todos::create_todo))
.route(
"/todos/{id}",
get(todos::get_todo)
.put(todos::update_todo)
.delete(todos::delete_todo),
);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The users.rs file did not change at all. The todos.rs file is completely independent. If a teammate is working on todo features and you are working on user features, you edit different files and never create a merge conflict with each other.
This is the pattern's biggest practical advantage in team environments: file boundaries become work boundaries. The file system itself prevents accidental interference between unrelated resources.
Naming Handler Functions Inside a Resource File
Within a single resource file, you want function names that clearly state both the resource and the operation. The standard convention uses the resource name as a prefix followed by the operation:
| Operation | Handler Function Name |
|---|---|
| List all users | list_users |
| Get one user | get_user |
| Create a user | create_user |
| Update a user | update_user |
| Delete a user | delete_user |
| List all todos | list_todos |
| Get one todo | get_todo |
| Create a todo | create_todo |
| Update a todo | update_todo |
| Delete a todo | delete_todo |
This convention means you can read a route definition in main.rs and immediately know where to find the handler. A route calling todos::update_todo points to the update_todo function inside todos.rs. No searching required.
Consistent names work together with the file organization. The file name tells you the resource, and the function name tells you the operation.
What Goes Inside a Resource File
A resource file should contain only the handler functions for that one resource. It should not contain routing configuration, application state definitions, database setup, or shared utilities.
Here is a more realistic users.rs that uses an extractor and returns JSON, while staying focused on the users resource:
// src/handlers/users.rs
use axum::{
Json,
extract::Path,
};
use serde_json::{json, Value};
pub async fn list_users() -> Json<Value> {
Json(json!({
"users": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
]
}))
}
pub async fn get_user(Path(id): Path<u32>) -> Json<Value> {
Json(json!({
"id": id,
"name": "Alice"
}))
}
pub async fn create_user() -> Json<Value> {
Json(json!({
"message": "user created"
}))
}
This example imports Json and Path from Axum. These are extractors - tools that pull information out of incoming requests. The Path extractor reads the {id} segment from the URL, and Json wraps the return value so Axum serializes it to JSON in the response body.
The key point is that all of this code is concerned with the users resource. Nothing in this file touches todos, products, or any other resource. When you open users.rs, you see only user-related logic.
Keeping Boundaries Clear:
A common beginner mistake is to put a helper function that several resources share - like a database connection helper or a validation function - inside users.rs because that is where you first needed it. Shared helpers belong in their own file, not inside a resource file. If you find yourself writing a function in users.rs that does not touch user data, it probably belongs somewhere else.
How the Router Stays Clean
One of the pleasant side effects of this pattern is that main.rs shrinks to a readable list of routes. Instead of hundreds of lines of handler implementations, main.rs becomes a directory of what your API does.
The router below also covers a third resource, products. Its file follows the same shape as the other two, so create src/handlers/products.rs first:
// src/handlers/products.rs
pub async fn list_products() -> &'static str {
"all products"
}
pub async fn get_product() -> &'static str {
"one product"
}
pub async fn create_product() -> &'static str {
"product created"
}
pub async fn update_product() -> &'static str {
"product updated"
}
pub async fn delete_product() -> &'static str {
"product deleted"
}
And add pub mod products; to src/handlers/mod.rs, next to the todos and users lines. Then the router in src/main.rs looks like this:
// src/main.rs
mod handlers;
use axum::{Router, routing::get};
use handlers::{products, todos, users};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users", get(users::list_users).post(users::create_user))
.route(
"/users/{id}",
get(users::get_user)
.put(users::update_user)
.delete(users::delete_user),
)
.route("/todos", get(todos::list_todos).post(todos::create_todo))
.route(
"/todos/{id}",
get(todos::get_todo)
.put(todos::update_todo)
.delete(todos::delete_todo),
)
.route(
"/products",
get(products::list_products).post(products::create_product),
)
.route(
"/products/{id}",
get(products::get_product)
.put(products::update_product)
.delete(products::delete_product),
);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The router now reads like a table of contents. Each line tells you the HTTP method, the URL path, and which function handles it. The implementation details are tucked away in the resource files where they belong.
Common Mistakes and How to Fix Them
Forgetting the mod Declaration
The single most common mistake is creating handlers/users.rs but forgetting to declare it as a module. When this happens, Rust does not know the file exists, and your router code in main.rs will fail to compile with an error like "cannot find module users in handlers."
// src/handlers/mod.rs - MISSING the users declaration
// This file is empty, but users.rs exists in the same directory.
The fix is one line:
// src/handlers/mod.rs - CORRECT
pub mod users;
Compile Error from Missing Module Declaration:
Creating a .rs file inside a directory does not automatically make it part of your Rust project. Rust only loads files that are explicitly declared as modules. A missing pub mod users; line in mod.rs causes a compile-time error, not a runtime error, so you will see it when you run cargo check or cargo build.
Making Handler Functions Private
Even if the module is declared correctly, the handler functions themselves need to be public. Rust functions default to private within their module.
// src/handlers/users.rs - WRONG: functions are private
async fn list_users() -> &'static str {
"all users"
}
This function cannot be called from main.rs because it is private to the users module. The router setup will fail with an error saying the function is private. The fix is adding pub:
// src/handlers/users.rs - CORRECT: function is public
pub async fn list_users() -> &'static str {
"all users"
}
Mixing Resources in One File
Another common mistake is creating a file called users.rs and then adding a todo handler to it "temporarily" because it is small enough. This defeats the purpose of the pattern. If a handler deals with todos, it belongs in todos.rs, even if it is only three lines long.
The boundary is not about file size - it is about conceptual grouping. A file with three user handlers and one todo handler is harder to understand than two files with clear responsibilities.
When This Pattern Is Too Much
Not every application needs a handlers directory with multiple resource files. If your entire API has only two or three routes and you do not expect it to grow, putting handlers directly in main.rs is perfectly fine. The pattern pays off when you have at least two resources, each with multiple operations.
A good rule of thumb: if your main.rs is under 100 lines and you can see every route at a glance, you do not need this organization yet. If you find yourself scrolling through main.rs to find a specific handler, that is the signal to start splitting files.
The organizational cost is also worth mentioning. The module system adds a small amount of boilerplate: the mod.rs file, the pub keywords, the use imports. For a tiny project, that boilerplate can feel heavier than the problem it solves. For a project that will grow, it is a one-time investment that pays off every day after.
Summary
The one-file-per-resource pattern solves a specific problem: handler functions for different resources getting tangled together in a single file. The solution is mechanical - a handlers directory with one file per resource, a mod.rs that declares each file as a module, and pub functions that the router can reach.
The single most important insight is that file names carry meaning. A file called todos.rs tells every developer on the project, before they open it, that every handler inside deals with todos. When the team grows and the API grows, that meaning saves real time.
If your application has one resource and you can see every route at a glance, keep your handlers in main.rs. The moment you add a second resource or find yourself searching for a handler, move to this pattern and do not look back.