Models Directory in Axum Project Structure
Learn how to organize data structures in a dedicated models directory within an Axum project, including serde serialization, request and response models, and common pitfalls.
A models/ directory is a folder inside your Axum project where you keep the data structures that represent the information your application works with. These structures are typically Rust structs and enums that describe things like users, products, orders, or any other concept your API deals with. They are separate from your route definitions and handler functions, which makes your code easier to read, test, and maintain.
Why Put Data Structures in Their Own Directory
Without a dedicated place for models, you might be tempted to define structs directly inside a handler file whenever you need them. That works for tiny examples but becomes messy quickly. Imagine three different handlers all needing a User struct. If you define it in each handler, you now have three copies that can drift apart. If you need to change what a user looks like - adding a field, renaming something - you have to hunt down every copy.
A models/ directory solves this by giving every data shape a single home. Handlers import what they need from there. Changes happen in one place, and every part of the application sees the same definition.
A mental model:
Think of models like blueprints for the objects your API sends and receives. Instead of describing a house every time you talk about it, you draw one blueprint and refer to it by name.
What You Typically Find in a Models Directory
Inside models/ you will usually see structs that fall into a few categories:
- Request models - the shape of data clients send to your API, like a JSON body for creating a new user.
- Response models - the shape of data your API sends back, which may hide internal fields or add computed ones.
- Database models - the shape of rows in your database, often with fields like
idandcreated_at. - Domain models - structures that represent core business concepts, which may be used across requests, responses, and internal logic.
You don't need all of these on day one. Start with the simplest thing that works, then add more as your project grows.
Creating the Models Directory Step by Step
If you are starting from a project that already has routes/ and handlers/, adding a models/ directory involves three small steps.
Step 1: Create the directory and module file
Create a new folder called models inside your src directory. Inside that folder, create a file named mod.rs. This file tells Rust that models is a module, and it will contain or re-export the actual model definitions.
src/
├── main.rs
├── lib.rs
├── routes/
├── handlers/
└── models/
└── mod.rs
Step 2: Add the module declaration to your crate root
In src/lib.rs (or src/main.rs if you don't have a lib), add the line pub mod models; so the compiler knows to look for the models directory.
// src/lib.rs
pub mod handlers;
pub mod routes;
pub mod models; // <-- new
Step 3: Define a model inside mod.rs
Open src/models/mod.rs and write your first struct. Keep it as plain as possible for now: two fields, no extra attributes.
// src/models/mod.rs
pub struct User {
pub id: u64,
pub name: String,
}
A Simple Model Without Serde
Step 3 gave you the absolute simplest model possible: a struct with two fields and no extra attributes. It lives in src/models/mod.rs, the entry point for the models module.
// src/models/mod.rs
pub struct User {
pub id: u64,
pub name: String,
}
This struct is public, and its fields are public. That means any other module in your crate can create a User and read its fields. The u64 is an unsigned 64-bit integer - a whole number that can't be negative. String is a growable piece of text.
But this struct can't be turned into JSON yet. Axum handlers often need to send JSON responses or receive JSON request bodies, and that requires two extra traits from the serde crate: Serialize and Deserialize. That is the next step.
Adding Serde So the Model Can Speak JSON
Serde is the crate that converts Rust values to JSON and back. To use it, add serde with the derive feature to your Cargo.toml, then add the derives to the struct:
# Cargo.toml
[dependencies]
serde = { version = "1", features = ["derive"] }
// src/models/mod.rs
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
pub id: u64,
pub name: String,
}
The #[derive(...)] line automatically generates code that implements those traits for your struct. Debug lets you print the struct with {:?} for debugging, Clone lets you make copies, and Serialize/Deserialize let you convert between Rust values and JSON (or other formats).
If you can compile this:
Your models module is set up correctly. Any handler can now import and use User. Run cargo check to confirm there are no errors.
Using the Model in a Handler
Now that User exists, let's see how a handler would use it. Suppose you have a handler that returns a list of users as JSON. It lives in a file like src/handlers/user_handler.rs, and like any handler file it must be declared in src/handlers/mod.rs with a line such as pub mod user_handler;, or the compiler will never see it.
// src/handlers/user_handler.rs
use axum::Json;
use crate::models::User;
pub async fn list_users() -> Json<Vec<User>> {
let users = vec![
User { id: 1, name: "Alice".to_string() },
User { id: 2, name: "Bob".to_string() },
];
Json(users)
}
The handler creates two User instances, puts them in a Vec (a growable array), wraps that in Json, and returns it. Axum automatically converts the Json wrapper into an HTTP response with Content-Type: application/json. The response body will look like this:
[
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
]
Notice that the JSON field names match the Rust field names exactly: id and name. Serde uses the field names as-is by default.
Missing serde derive is the most common beginner mistake:
If you forget to add Serialize to a struct you return as Json, the compiler will give you an error like "the trait bound User: Serialize is not satisfied." The fix is always to add #[derive(Serialize)] (and usually Deserialize too) to the struct.
Request Models vs Response Models
Sometimes the data a client sends is different from what you store or what you send back. For example, when creating a user, the client might send only name and email, but your database row also has an id and a created_at timestamp. Using one struct for everything would force you to make id optional or fill it with placeholder values.
A clean approach is to define separate structs for different purposes. Here is a common pattern:
// src/models/mod.rs
use serde::{Deserialize, Serialize};
// The shape of the JSON a client sends when creating a user.
#[derive(Debug, Clone, Deserialize)]
pub struct CreateUserRequest {
pub name: String,
pub email: String,
}
// The full user record, including fields the server generates.
#[derive(Debug, Clone, Serialize)]
pub struct User {
pub id: u64,
pub name: String,
pub email: String,
}
Notice that CreateUserRequest only derives Deserialize because it will only be read from request bodies. User only derives Serialize because it will only be written to response bodies. You can derive both if needed, but being selective makes your intent clear.
A handler that creates a user might look like this:
// src/handlers/user_handler.rs
use axum::{Json, http::StatusCode};
use crate::models::{CreateUserRequest, User};
pub async fn create_user(
Json(payload): Json<CreateUserRequest>,
) -> (StatusCode, Json<User>) {
// Pretend we saved to a database and got an ID back.
let new_user = User {
id: 42,
name: payload.name,
email: payload.email,
};
(StatusCode::CREATED, Json(new_user))
}
The handler extracts the JSON body into CreateUserRequest, builds a User with a hardcoded ID, and returns a 201 Created status along with the new user as JSON.
Why split request and response models?:
Separating them lets you change the API request format without touching your internal representation. For instance, you could later add a password field to CreateUserRequest but never include it in User. It also protects you from accidentally exposing internal fields.
Organizing Models Into Multiple Files
As your project grows, a single mod.rs can become long. You might want to split models into one file per domain concept. For example, user.rs, product.rs, order.rs.
Here are two common ways to organize this. Choose the one that fits your project size.
Keep everything in src/models/mod.rs. Works well for small projects with only a handful of models.
// src/models/mod.rs
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
pub id: u64,
pub name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Product {
pub id: u64,
pub title: String,
pub price_cents: u64,
}
Both approaches result in the same public API: handlers can still use crate::models::User and crate::models::Product. The multiple-file version just keeps each struct in its own file, which is easier to navigate when you have many models.
Customizing JSON Field Names
Sometimes the JSON keys you want to expose don't match Rust naming conventions. For example, Rust prefers snake_case, but many APIs use camelCase for JSON. Serde lets you rename fields using attributes.
// src/models/user.rs
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct User {
pub id: u64,
pub first_name: String,
pub last_name: String,
}
With rename_all = "camelCase", serde automatically converts first_name to firstName and last_name to lastName when serializing to JSON and back. The response for a user would look like:
{
"id": 1,
"firstName": "Alice",
"lastName": "Smith"
}
You can also rename individual fields:
// src/models/user.rs
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
pub id: u64,
#[serde(rename = "displayName")]
pub name: String,
}
Now the name field will appear as displayName in JSON.
Rename attributes only change the wire format:
The Rust code still uses the original field names (first_name, name). Renaming only affects how serde maps between Rust and JSON. A plain rename applies to both directions, reading and writing, so the same spelling is used on the way in and the way out. If you ever need different spellings for each direction, serde has separate forms for that: #[serde(rename(serialize = "displayName", deserialize = "name"))].
Models with Enums
Enums are useful when a field can only take a limited set of values. For example, a community member's role might be Admin, Moderator, or Regular. This example uses its own struct, Member, so it does not clash with the User struct from the earlier sections.
// src/models/member.rs
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
Admin,
Moderator,
Regular,
}
impl Default for Role {
fn default() -> Self {
Role::Regular
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Member {
pub id: u64,
pub name: String,
pub role: Role,
}
With rename_all = "lowercase", the variants become "admin", "moderator", and "regular" in JSON. A member with role Admin will serialize as:
{
"id": 7,
"name": "Carol",
"role": "admin"
}
When deserializing, serde matches the JSON string to the enum variant case-sensitively after applying the rename rule. So "admin" becomes Role::Admin, but "Admin" is rejected with unknown variant - the rename only changes the expected spelling, it does not make matching case-insensitive. Because this model lives in its own file, declare it in src/models/mod.rs with pub mod member;, alongside the other model modules.
Working with External Types
Real-world models often include types from other crates, like chrono::DateTime for timestamps or uuid::Uuid for unique identifiers. Serde has built-in support for many common types if you enable the right features.
For example, to use Uuid and DateTime<Utc>:
# Cargo.toml
[dependencies]
serde = { version = "1", features = ["derive"] }
uuid = { version = "1", features = ["serde", "v4"] }
chrono = { version = "0.4", features = ["serde"] }
Then you can include them in your model:
// src/models/user.rs
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
pub id: Uuid,
pub name: String,
pub created_at: DateTime<Utc>,
}
Serde knows how to serialize Uuid as a string (like "550e8400-e29b-41d4-a716-446655440000") and DateTime<Utc> as an RFC 3339 timestamp string (like "2026-08-31T12:34:56Z"). You don't need to write any custom code for that.
Feature flags are important:
The serde feature on uuid and chrono enables the Serialize and Deserialize implementations for those types. Without those features, the compiler will say those types don't implement the traits, and you'll be stuck. Always check the crate's documentation for the correct feature flag.
Making Fields Public or Private
In the examples so far, all fields are pub. That's convenient because handlers in other modules can construct and read the structs directly. But sometimes you want to hide internal details. For request models, making fields public is usually fine because the handler needs to read them. For response models, you might want to make fields private and provide getter methods, but that's more common in larger applications.
Here's a model with private fields and a constructor:
// src/models/user.rs
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
id: u64,
name: String,
}
impl User {
pub fn new(id: u64, name: String) -> Self {
Self { id, name }
}
pub fn id(&self) -> u64 {
self.id
}
pub fn name(&self) -> &str {
&self.name
}
}
Handlers outside the models module cannot access user.id directly, but they can call user.id() to get the value. This gives you more control over how the struct is used and lets you change the internal representation later without breaking callers.
Private fields break construction from other modules:
If you make fields private and don't provide a public constructor or getters, handlers will not be able to create or inspect the struct. This is a common source of "field id is private" errors. Decide early whether you want a simple public data holder or a more encapsulated type.
Adding Basic Validation
Serde itself doesn't validate business rules, but you can use attributes like #[serde(default)] to handle missing fields gracefully, or combine with other crates like validator. For simple cases, you can add custom validation after deserialization.
Here's an example that defaults role to Regular if the field is missing in the incoming JSON. It reuses the Role enum from the previous section and defines its own request struct, so it does not clash with the CreateUserRequest from earlier:
// src/models/user.rs
use serde::{Deserialize, Serialize};
use crate::models::member::Role;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateUserWithRole {
pub name: String,
#[serde(default)]
pub role: Role,
}
Now a JSON body like {"name": "Dave"} will deserialize into CreateUserWithRole { name: "Dave".to_string(), role: Role::Regular }. Without #[serde(default)], omitting role would cause an error because serde expects the field to be present.
Putting It All Together in a Handler
Let's see a complete example of a handler that uses the request and response models from earlier on this page: CreateUserRequest with name and email, and User with id, name, and email.
// src/handlers/user_handler.rs
use axum::{Json, http::StatusCode};
use crate::models::{CreateUserRequest, User};
pub async fn create_user(
Json(payload): Json<CreateUserRequest>,
) -> (StatusCode, Json<User>) {
// Here you would insert into a database and get an ID.
let new_user = User {
id: 100,
name: payload.name,
email: payload.email,
};
(StatusCode::CREATED, Json(new_user))
}
If a client sends this JSON body:
{
"name": "Eve",
"email": "eve@example.com"
}
The handler will extract it into CreateUserRequest, create a User with id: 100, and return a 201 Created response with:
{
"id": 100,
"name": "Eve",
"email": "eve@example.com"
}
What Not to Put in Models
The models directory is for data shapes, not business logic. Avoid putting database queries, route definitions, or complex processing inside model files. If you find yourself writing functions that talk to a database or read files, that logic belongs in a separate service or database module. Keeping models purely as data containers keeps them easy to reuse and test.
Model files should not import handlers or routes:
If you import a handler inside a model file, you're creating a circular dependency that makes your project hard to understand. Rust itself allows modules in the same crate to reference each other in a cycle, so the compiler will not stop you - the problem is architectural, not a compile error. Models should only depend on external crates and possibly other models.
Summary
A models/ directory is the home for the structs and enums that define your application's data. It separates data shapes from routing and handling logic, making your Axum project easier to grow and maintain. You start with simple structs and add serde derives to work with JSON. As your API evolves, you can split request and response models, rename fields for external compatibility, and incorporate enums and external types like UUIDs and timestamps.
The most important takeaway is that models give every piece of data a single source of truth. When you need to change what a user looks like, you change it in one file, and every handler that uses it automatically sees the new shape.
Once you have a place for models, the next structural piece many Axum projects add is a dedicated module for shared application state, so your handlers can access things like database connections or configuration without passing them around manually.