get_user function

Learn how to write the get_user handler function in Axum, covering async signatures, return type choices, and common beginner mistakes.

A get_user function is an async function that responds to HTTP GET requests asking for one particular user. The name follows a REST API naming convention: "get" means read a single resource, and "user" is the resource type. When a client visits a URL like GET /users/42, Axum routes that request to a handler named something like get_user.

In Axum, a handler is just an async function that takes zero or more extractors - data pulled from the incoming request - and returns something that can become an HTTP response. You can picture a handler like a receptionist at a front desk: a visitor walks up with a request, the receptionist processes it, and then gives back an answer. The get_user receptionist answers specifically when someone asks to see one user.

This page focuses on writing that function. The file src/handlers/users.rs already exists, so you will fill it with the actual function body.

The Simplest Possible get_user

Start with the smallest version that compiles. This confirms the function works end-to-end before you add more moving parts.

// src/handlers/users.rs
pub async fn get_user() -> &'static str {
    "User data"
}

When Axum calls this function, it receives the string "User data" and converts it into an HTTP response with status code 200 OK and that string as the response body. The return type &'static str means the text is baked into the compiled program and lives for the entire runtime. That works fine for hardcoded text but becomes limiting once you need dynamic content.

Breaking Down the Function Signature

Every keyword in the signature has a purpose. Learning them one by one prevents confusion when Rust produces an error message later.

pub makes the function visible outside the users module. In Rust, items inside a module are private by default. Without pub, the router living in main.rs or another module cannot reference get_user.

async fn tells Rust this function returns a future - a value representing work that has not finished yet. Axum runs on an async runtime called Tokio, and every handler must be async so the server can process many requests without blocking.

get_user() is the name. It follows the convention for reading one resource from a collection.

-> &'static str declares the return type. The arrow means "this function returns," and &'static str is the type of the returned value.

The body { "User data" } produces the actual response content. Since this version has no await points inside it, the function runs to completion synchronously when called.

Why async when there is no await?:

You might wonder why the function is async when nothing inside it awaits. Axum requires handlers to be async functions because real handlers typically perform async work - reading from a database, calling an external API, or waiting for file I/O. Marking the function async from the beginning keeps it compatible with Axum's handler requirements, even if this first version does not await anything.

Choosing a Return Type

Axum accepts many different return types. The choice depends on what kind of data you need to send back to the client. Here are the common options, and when each one fits.

Returning a String

A String is an owned, growable text value. Use this when the response text is assembled at runtime rather than hardcoded.

// src/handlers/users.rs
pub async fn get_user() -> String {
    "User data".to_string()
}

The to_string() method converts the static string slice into an owned String. Axum knows how to turn a String into an HTTP response body automatically. This is the most common return type for plain text responses.

Returning JSON

For a user API, plain text is rarely useful. Most APIs exchange data as JSON, short for JavaScript Object Notation - a text format for structured data that every modern programming language can parse.

// src/handlers/users.rs
use axum::Json;
use serde_json::{json, Value};
pub async fn get_user() -> Json<Value> {
    Json(json!({
        "id": 1,
        "name": "Alice",
        "email": "alice@example.com"
    }))
}

The Json type wraps a serializable value and tells Axum to set the response header Content-Type to application/json. The json! macro from the serde_json crate builds a JSON value from the code inside the curly braces. The Value type is a generic container that can hold any valid JSON data.

When a client sends a GET request to this handler, they receive a response body like this:

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

The keys appear in alphabetical order because serde_json::Value stores object keys sorted that way. The Content-Type header is set to application/json automatically, which is what tells the client how to interpret the body.

Using impl IntoResponse

Sometimes the concrete return type is long and awkward to write out, for example a nested tuple of status, headers, and JSON. impl IntoResponse lets you hide that one concrete type behind the trait name. This Rust feature says: "this function returns some type that implements the IntoResponse trait, but I am not naming exactly which one." The key word is one - every code path must still return the same concrete type.

// src/handlers/users.rs
use axum::response::IntoResponse;
pub async fn get_user() -> impl IntoResponse {
    "User data"
}

This compiles because &str, String, Json<T>, and many other types all implement IntoResponse. The impl keyword lets Rust determine the concrete type at compile time. The benefit is that you can swap the concrete type later - say from String to Json<Value> - without touching the signature, as long as the whole function returns that one new type.

impl IntoResponse hides one type, not many:

If you declare -> String and then try to return a Json<Value> from the same function, Rust produces a compile error because the types do not match. Note that impl IntoResponse does not fix that: it still hides exactly one concrete type, so different branches returning different types will not compile either. Use impl IntoResponse when you want to hide a long concrete type (for example a deeply nested tuple) without changing what the function returns. If different code paths genuinely need different types, return an enum or a Result<T, E> where both sides implement IntoResponse, or return Response directly. For a function that always returns the same type, a concrete type like String or Json<Value> is clearer and gives better compiler feedback.

Why the Name get_user

The function name follows a convention used across many APIs and frameworks. In a REST API - REST stands for Representational State Transfer, a style of designing web APIs around resources - the standard operations map to four actions:

  • Create - add a new resource
  • Read - fetch one or more resources
  • Update - change an existing resource
  • Delete - remove a resource

These four actions form the acronym CRUD. For a users resource, the Read action splits into two handlers:

  • get_users or list_users - returns a collection of all users
  • get_user - returns a single user, usually identified by an ID in the URL

So get_user specifically means "read one user." The name communicates what the function does without anyone needing to read its body. As an application grows to dozens of handlers, consistent naming becomes a form of documentation.

Predictable names are working names:

When another developer sees get_user, they immediately know three things: this handles GET requests, it returns one user, and it probably needs a user ID to know which one. That predictability is exactly what the convention exists to provide.

Where the Function Lives

The function belongs in src/handlers/users.rs, the file dedicated to all handlers for the users resource. Keeping related handlers in one file is a standard organization pattern: one file per resource.

// src/handlers/users.rs
pub async fn get_user() -> String {
    "User data".to_string()
}

The pub keyword is what allows the router to register this function on a route. Without it, any attempt to reference get_user from outside the users module produces a compile error about a private item.

Running the Simplest get_user End to End

The function on its own does nothing until a route points at it. Here is the smallest complete wiring: the module declaration and route in main.rs, with the JSON version of the handler in users.rs.

// src/main.rs
mod handlers;
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new().route("/users", get(handlers::users::get_user));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}
// src/handlers/users.rs
use axum::Json;
use serde_json::{json, Value};
pub async fn get_user() -> Json<Value> {
    Json(json!({
        "id": 1,
        "name": "Alice",
        "email": "alice@example.com"
    }))
}

This needs serde_json in Cargo.toml alongside axum and tokio:

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

Run it with cargo run, then request the route:

curl http://127.0.0.1:3000/users

You get back the JSON body with a 200 OK status:

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

Every get_user on this page wires up the same way. Only the handler body and return type change - the route registration stays one line. This assumes src/handlers/mod.rs declares the module with pub mod users;, since Rust only loads files that are declared as modules.

Common Beginner Mistakes

Forgetting pub

// Wrong - this function is private to the users module
async fn get_user() -> &'static str {
    "User data"
}

Without pub, the function cannot be seen from main.rs or a router module. The compiler reports that the function is private when you try to register it on a route.

Forgetting async

// Wrong - Axum expects an async function
pub fn get_user() -> &'static str {
    "User data"
}

Axum's get() routing function requires an async handler. Passing a synchronous function produces a confusing trait bound error - the compiler says something like "the trait bound fn() -> &str: Handler<_, _> is not satisfied." If you see that message, check whether the function is missing the async keyword.

Mismatched return type

// Wrong - the body returns Json<Value>, not String
use axum::Json;
use serde_json::{json, Value};
pub async fn get_user() -> String {
    Json(json!({"id": 1}))
}

The function declares it returns String, but the body produces a Json<Value>. Rust refuses to compile because the declared type and the actual type do not match. Fix this by either changing the signature to Json<Value> or using impl IntoResponse.

Handler trait bound errors are vague:

When Axum says a function "does not implement Handler," the root cause is usually one of three things: the function is not async, the return type does not implement IntoResponse, or an argument type fails to implement the required extractor trait. Rust points at the trait bound rather than the actual mistake, which makes the error hard to read. When you encounter it, check the function signature line by line before changing anything else.

Summary

The get_user function is a handler that responds to GET requests for one user. Its core shape is an async function marked pub so the router can see it, returning a type Axum can convert into an HTTP response. The name encodes the CRUD convention for reading a single resource, and the return type choice - String, Json, or impl IntoResponse - depends on what kind of data the client expects.

The most important insight is that a handler's job is deliberately narrow: receive a request and produce a response. The get_user function does not care how the request arrived or what transport delivered it. That separation is what keeps handlers reusable and testable.

The natural next step is to teach get_user how to read the user ID from the URL path, so it can return the specific user the client asked for instead of a hardcoded value.