Placeholder User value

Learn how to return a placeholder user object from an Axum handler before connecting to a real data source.

When you build a get_user handler, you often start with a hardcoded response before wiring up a database or an external API. This hardcoded response is a placeholder user value. It gives you a concrete shape to work with, lets you test the endpoint, and defines the JSON structure the frontend will eventually rely on.

What a Placeholder User Value Is

A placeholder user value is a simple, hand-written instance of a User struct that your handler returns every time someone calls the endpoint. It is not real data. It exists so you can build and test the handler without a database or any other source of truth.

Why is this useful? Imagine you are building an API where GET /users/1 should return a JSON object with id, name, and email. You have not decided how to store users yet - maybe you will use PostgreSQL, maybe a file, maybe an in‑memory cache. Writing the handler to fetch from a database now would force you to set up the entire storage layer before you can even see a response in your browser.

A placeholder lets you skip that setup. You define the response shape, return a fake user, and verify that routing, serialization, and status codes all work. Later, you replace the fake data with a real lookup. This keeps your development moving forward in small, testable steps.

A get_user handler that extracts a user ID from the URL path looks like this before it returns anything:

async fn get_user(Path(user_id): Path<u64>) {
    // nothing returned yet
}

Now we will fill in the return type and give it a placeholder body.

Defining the User Struct

Before the handler can return a user, you need a type that describes what a user is. In Rust, you do that with a struct.

Create a User struct with a few fields that make sense for your API. Derive Serialize from serde so Axum can convert the struct to JSON automatically.

// src/handlers/users.rs
use serde::Serialize;
#[derive(Serialize)]
pub struct User {
    pub id: u64,
    pub name: String,
    pub email: String,
}

Let's unpack this.

  • pub struct User defines a new data type named User.
  • The fields id, name, and email each have a type. u64 is an unsigned 64‑bit integer (only positive whole numbers). String holds text.
  • #[derive(Serialize)] tells Rust to automatically generate the code needed to turn a User value into a JSON string. Without this derive, Axum would not know how to serialize the struct and the code would not compile.

The serde crate must be in your Cargo.toml. If you haven't added it yet, here is the relevant dependency section:

[dependencies]
axum = "0.8"
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["full"] }

Why Serialize and not Deserialize:

Returning data from a handler only requires Serialize - you are converting a Rust value into JSON. If you later want to accept a user as input (like in a POST request body), you will also need Deserialize. For now, Serialize is enough.

Returning a Simple Placeholder from the Handler

Now that you have a User type, make the get_user handler return a hardcoded User wrapped in Axum's Json extractor.

// src/handlers/users.rs
use axum::{
    extract::Path,
    Json,
};
use serde::Serialize;
#[derive(Serialize)]
pub struct User {
    pub id: u64,
    pub name: String,
    pub email: String,
}
pub async fn get_user(Path(user_id): Path<u64>) -> Json<User> {
    Json(User {
        id: user_id,
        name: String::from("Alice"),
        email: String::from("alice@example.com"),
    })
}

Here, the function returns Json<User>. Json is an Axum type that tells the framework "this is a JSON response, set the correct Content-Type header, and serialize the contained value." The handler ignores any real data source and always constructs the same user, but it uses the user_id from the path to set the id field. That way the response looks dynamic even though the name and email are fixed.

When you run this and visit http://localhost:3000/users/1, you will see:

{
  "id": 1,
  "name": "Alice",
  "email": "alice@example.com"
}

For http://localhost:3000/users/42, the id changes to 42, but name and email remain the same. That is the placeholder behavior: enough variation to feel real, not enough logic to require a database.

If you see JSON like the example above, your placeholder works:

A successful placeholder response proves that the route is registered, the path extractor works, the User struct is serializable, and Axum can convert it to JSON. Those are the foundation stones for the real handler later.

Building a Placeholder That Uses the Path ID Creatively

A placeholder does not have to be completely static. You can use the extracted user_id to generate a more interesting mock response. For example, you might create a name that includes the ID.

Here is a version that varies the name based on the ID:

// src/handlers/users.rs
use axum::{extract::Path, Json};
use serde::Serialize;
#[derive(Serialize)]
pub struct User {
    pub id: u64,
    pub name: String,
    pub email: String,
}
pub async fn get_user(Path(user_id): Path<u64>) -> Json<User> {
    let name = format!("User #{user_id}");
    let email = format!("user{user_id}@example.com");
    Json(User {
        id: user_id,
        name,
        email,
    })
}

The format! macro creates a String by inserting values into a template. format!("User #{user_id}") produces something like "User #7" when user_id is 7. The email field becomes user7@example.com. This is still a placeholder - no real user data - but it gives a more realistic response for testing frontends that may display the name and email.

Alternative Ways to Return the Placeholder

Axum is flexible about what a handler can return. You are not limited to Json<User>. The most common alternatives are:

  1. Return impl IntoResponse for future flexibility.
  2. Return a tuple like (StatusCode, Json<User>) to control the HTTP status code.
  3. Return a custom error type when the user is not found.

Let's look at each.

Returning impl IntoResponse

If you want to hide a long concrete return type without changing what the function returns, you can return impl IntoResponse. This tells Rust that the handler returns something that can be turned into an HTTP response, without spelling out exactly what that something is. Note that it is still exactly one concrete type - if you later need different types for success and failure, use a Result (or an enum) instead, as shown below.

// src/handlers/users.rs
use axum::{
    extract::Path,
    http::StatusCode,
    response::IntoResponse,
    Json,
};
use serde::Serialize;
#[derive(Serialize)]
pub struct User {
    pub id: u64,
    pub name: String,
    pub email: String,
}
pub async fn get_user(Path(user_id): Path<u64>) -> impl IntoResponse {
    let user = User {
        id: user_id,
        name: String::from("Alice"),
        email: String::from("alice@example.com"),
    };
    (StatusCode::OK, Json(user))
}

Here the return type is impl IntoResponse. The function body returns a tuple (StatusCode::OK, Json(user)). Both StatusCode and Json implement IntoResponse, and Axum knows how to combine a tuple of response parts into a full response. StatusCode::OK is the HTTP 200 code, which means "success."

This approach is useful when you want to later add an error branch. But note that the two branches must still share one concrete return type - impl IntoResponse does not let you return a different type per branch. For success-or-error, return a Result whose both sides implement IntoResponse, and define the error shape first:

// src/handlers/users.rs
use axum::{
    extract::Path,
    http::StatusCode,
    Json,
};
use serde::Serialize;
#[derive(Serialize)]
pub struct User {
    pub id: u64,
    pub name: String,
    pub email: String,
}
#[derive(Serialize)]
pub struct ErrorResponse {
    pub message: String,
}
pub async fn get_user(Path(user_id): Path<u64>) -> Result<Json<User>, (StatusCode, Json<ErrorResponse>)> {
    if user_id == 0 {
        return Err((StatusCode::BAD_REQUEST, Json(ErrorResponse { message: "Invalid user ID".to_string() })));
    }
    let user = User {
        id: user_id,
        name: String::from("Alice"),
        email: String::from("alice@example.com"),
    };
    Ok(Json(user))
}

But that is moving into error handling territory. For now, the placeholder can stay simple.

Returning Only Json Without a Status Code

Axum automatically sets the status code to 200 OK when you return Json directly. That is the simplest form and perfectly fine for a placeholder. It is the handler shown at the start of this page: Json<User> as the return type, with the User built inline and no status code anywhere in sight.

Returning Json without StatusCode is always 200 OK:

If you later want to return a 404 Not Found for missing users, returning Json directly will still respond with 200. You must switch to a return type that includes StatusCode or a custom error type. Keep that in mind when you move from placeholder to real logic.

Wiring the Placeholder into a Router (Minimal Context)

The get_user handler must be registered in a router for the endpoint to work. In your main application file, you would have something like this:

// src/main.rs
mod handlers;
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users/{user_id}", get(handlers::users::get_user));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

This route pattern /users/{user_id} matches URLs like /users/1, /users/42, and so on. The get function connects the HTTP GET method to your get_user handler. When a request arrives, Axum extracts the user_id from the path and calls your handler with that value.

The placeholder user response then flows back through Axum, gets serialized to JSON, and is sent to the client.

The mod handlers; line only works if Rust can find the handlers module. That means either a src/handlers.rs file or a src/handlers/mod.rs file that declares the users submodule:

// src/handlers/mod.rs
pub mod users;

If you use the single-file layout instead, the same line lives in src/handlers.rs. Either layout works; pick one and keep it consistent.

Do not forget to make the module and handler public:

The mod handlers; line in main.rs only works if you have a src/handlers.rs file or a src/handlers/mod.rs file that declares the users module. Inside src/handlers/users.rs, the get_user function must be marked pub so the router can call it from outside the module. Missing pub on the function or forgetting to declare the module will produce a compile error about privacy.

What You See When You Run the Placeholder

After you write the placeholder code and start the server with cargo run, open a browser or use curl.

For the simple Json<User> version, request http://localhost:3000/users/5:

curl http://localhost:3000/users/5

You should see:

{"id":5,"name":"Alice","email":"alice@example.com"}

If you added the dynamic formatting version, the response might be:

{"id":5,"name":"User #5","email":"user5@example.com"}

The exact output depends on which placeholder implementation you chose. The important part is that the response is valid JSON, has a 200 status code, and the id field matches the number in the URL.

Confirm your placeholder is working before moving on:

If you see a JSON object with the correct id, your handler, path extraction, serialization, and routing are all functioning. This is the green light to proceed to more advanced topics like real data retrieval, error handling, and state management.

Common Mistakes with Placeholder User Values

Beginners often hit a few roadblocks when writing placeholder handlers. Here are the most frequent ones and how to recognize them.

Forgetting to Derive Serialize

Without #[derive(Serialize)], Rust cannot convert your User struct to JSON. You will get a compile error that looks something like:

error[E0277]: the trait bound `User: Serialize` is not satisfied

The fix is to add #[derive(Serialize)] above the struct definition and make sure serde is in your Cargo.toml with the derive feature enabled.

Forgetting to Import Json

Json comes from axum::Json. If you write Json<User> without importing it, the compiler will say Json is not found. Add use axum::Json; at the top of the file.

Using &str Instead of String in the Struct

If you define a field as &str (a string slice), the struct will have a lifetime parameter and become much harder to use. For a placeholder, always use String for text fields. String is an owned, growable string type that plays nicely with serialization.

Trying to Return a Non-Serializable Type

Only types that implement Serialize can be wrapped in Json. If you add a field with a type that does not implement Serialize - for example std::fs::File, or a function pointer - you need to either avoid that type or convert it to something serializable first. (std::net::IpAddr is fine, by the way: serde implements Serialize for it.) Stick to primitives like u64, String, bool, and Vec for your placeholder.

Placeholder structs should be plain data:

Resist the urge to add complex logic or dependencies to your User struct just for the placeholder. Keep it a simple data container. You will thank yourself later when you connect a real database and need to map database rows to this struct.

Expanding the Placeholder: Multiple Users

A placeholder can return more than one user. If you are building a list_users handler, you might return a Vec<User> wrapped in Json. The idea is the same: hardcode an array of fake users.

// src/handlers/users.rs
use axum::Json;
use serde::Serialize;
#[derive(Serialize)]
pub struct User {
    pub id: u64,
    pub name: String,
    pub email: String,
}
pub async fn list_users() -> Json<Vec<User>> {
    let users = vec![
        User {
            id: 1,
            name: String::from("Alice"),
            email: String::from("alice@example.com"),
        },
        User {
            id: 2,
            name: String::from("Bob"),
            email: String::from("bob@example.com"),
        },
        User {
            id: 3,
            name: String::from("Charlie"),
            email: String::from("charlie@example.com"),
        },
    ];
    Json(users)
}

This handler returns a JSON array of three user objects. The pattern is identical to the single-user placeholder, just with a vector.

A Mental Model for Placeholders

Think of a placeholder user value like a stage prop in a theater rehearsal. The actors need to practice their lines and blocking before the real furniture and costumes arrive, so they use cardboard boxes and plain chairs. The play still works - you can see the interactions, test the timing, and discover problems.

Your User struct is the shape of the real furniture. The hardcoded values are the cardboard boxes. They let you test the entire HTTP flow - routing, path extraction, serialization, response headers - without waiting for a database to be installed. When the real storage is ready, you replace the cardboard with real furniture, but the shape stays the same.

This mental model also helps you avoid premature complexity. Do not try to build the entire database layer inside the placeholder handler. Keep the placeholder dumb, and keep the real logic separate.

Summary

A placeholder user value is a temporary, hardcoded instance of a data struct that your handler returns instead of real data. It lets you verify routing, path extraction, serialization, and response formatting before integrating a database or external service.

The most important insight is that a placeholder is not a hack - it is a deliberate development tool. It front-loads the shape of your API so that frontend and backend teams can work in parallel. When you are ready, you swap the hardcoded values for real database queries, and the rest of the handler remains unchanged.

The decision to make is which return shape to start with. Use plain Json<User> while the endpoint can only succeed, because it is the shortest correct form. Switch to (StatusCode, Json<User>) the moment you need a status code other than 200, and to Result<Json<User>, (StatusCode, Json<ErrorResponse>)> the moment the handler can fail for a reason the client should know about. Each step keeps the same User shape, so the frontend never has to change while the backend grows up around it.