Building a list_users Handler with Query Pagination
Learn how to create a list_users handler in Axum that uses the Query extractor for pagination, optional filters, and returning JSON user lists with default values and error handling.
A list_users handler is one of the most common endpoints you will build in a backend API. It answers GET /users and returns a collection of users. In a real application you would fetch these users from a database, but for this lesson we will keep everything in memory so the focus stays on how the handler receives and processes query parameters.
The Query extractor reads the ?key=value part of the URL into a struct you define, deriving serde::Deserialize. This page concentrates on assembling a complete, realistic list_users handler that does something useful with the extracted parameters.
The examples on this page use these dependencies in Cargo.toml:
[dependencies]
axum = "0.8"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }
tower = { version = "0.5", features = ["util"] }
serde_json is needed for the error-handling example that builds a JSON error object, and tower is needed for the testing example at the end. The json feature of axum is on by default, so Json works with a plain axum = "0.8" dependency.
A First Handler Without Any Query Parameters
Start with the smallest possible version. This handler ignores the query string entirely and always returns the same hardcoded list of users.
use axum::{extract::Query, routing::get, Json, Router};
use serde::Serialize;
#[derive(Serialize)]
struct User {
id: u64,
name: String,
}
async fn list_users() -> Json<Vec<User>> {
let users = vec![
User { id: 1, name: "Alice".to_string() },
User { id: 2, name: "Bob".to_string() },
User { id: 3, name: "Carol".to_string() },
];
Json(users)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/users", get(list_users));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
There are no surprises here. The handler returns Json<Vec<User>> because Vec<User> implements Serialize via the derive macro. When you run this and send GET /users, you get a JSON array of user objects.
You have a working baseline:
If you see [{"id":1,"name":"Alice"},{"id":2,"name":"Bob"},{"id":3,"name":"Carol"}] in your HTTP response, the basic setup is correct. Everything else in this page will add query parameter handling on top of this skeleton.
Adding a Pagination Struct
Now suppose the list of users is long, and clients should be able to request only a slice of it using page and limit query parameters. This is exactly where the Query extractor shines. Instead of parsing the query string manually, you define a struct whose fields match the expected parameter names, derive Deserialize, and let Axum do the work.
use axum::{extract::Query, routing::get, Json, Router};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct Pagination {
page: Option<u32>,
limit: Option<u32>,
}
#[derive(Clone, Serialize)]
struct User {
id: u64,
name: String,
}
async fn list_users(Query(pagination): Query<Pagination>) -> Json<Vec<User>> {
let page = pagination.page.unwrap_or(1);
let limit = pagination.limit.unwrap_or(10);
let all_users = vec![
User { id: 1, name: "Alice".to_string() },
User { id: 2, name: "Bob".to_string() },
User { id: 3, name: "Carol".to_string() },
User { id: 4, name: "Dave".to_string() },
User { id: 5, name: "Eve".to_string() },
User { id: 6, name: "Frank".to_string() },
];
let start = (page.saturating_sub(1) * limit) as usize;
let end = (start + limit as usize).min(all_users.len());
let users = if start >= all_users.len() {
Vec::new()
} else {
all_users[start..end].to_vec()
};
Json(users)
}
Here the handler signature includes Query(pagination): Query<Pagination>. Axum looks at the Pagination struct, sees two optional fields page and limit, and attempts to extract values from the request's query string. If a parameter is missing, because the field is Option<u32>, Serde sets it to None and extraction still succeeds. Inside the handler we call unwrap_or to replace None with sensible defaults: page 1 and limit 10.
The pagination logic calculates the starting index and ending index into the hardcoded all_users vector. It also guards against requesting a page that is beyond the available data, returning an empty array instead of a slice error. Note the use of saturating_sub(1): a plain page - 1 would panic on page=0 in debug builds (unsigned subtraction overflow), and page=0 is a value any client can send. With saturating_sub, page=0 behaves like page 1.
Why Option is the right choice for pagination:
Query parameters are inherently optional from the HTTP perspective. A user may type /users?page=2 without limit, or /users with no parameters at all. Marking the fields as Option makes your handler robust to all of those cases without any extra code.
Handling Invalid Query Values
What happens if a client sends /users?page=abc? The string "abc" cannot be converted into a u32, so Serde fails and the Query extractor rejects the request. Axum then returns a 400 Bad Request response with a plain text error body, and your handler never runs.
Sometimes you want more control over that rejection - for example, to return a JSON error message instead of plain text. You can do that by changing the extractor argument to Result<Query<Pagination>, QueryRejection>.
use axum::{
extract::{rejection::QueryRejection, Query},
http::StatusCode,
response::{IntoResponse, Response},
routing::get,
Json, Router,
};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct Pagination {
page: Option<u32>,
limit: Option<u32>,
}
#[derive(Serialize)]
struct User {
id: u64,
name: String,
}
async fn list_users(
pagination: Result<Query<Pagination>, QueryRejection>,
) -> Response {
let Query(pagination) = match pagination {
Ok(query) => query,
Err(_) => {
return (
StatusCode::BAD_REQUEST,
Json(serde_json::json!({
"error": "Invalid query parameters"
})),
)
.into_response();
}
};
let page = pagination.page.unwrap_or(1);
let limit = pagination.limit.unwrap_or(10);
// ... same user data and slicing as before ...
Json(serde_json::json!({
"page": page,
"limit": limit,
"users": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
]
}))
.into_response()
}
In this version, the QueryRejection type catches all possible failures while extracting query parameters. When an error occurs, we return a JSON object with a clear message and a 400 status. The happy path continues as before, but the response now includes pagination metadata alongside the user list, which is a common API pattern.
The extractor rejection happens before your handler runs:
If you do not wrap Query in a Result, any bad query string will bypass your handler entirely and return Axum's default error response. If your API contract requires JSON errors, you must use the Result pattern shown above.
Returning Rich Pagination Metadata
Many real APIs return not just the array of users but also information about the current page, the page size, and maybe the total number of items. This helps the client render pagination controls. Let's define a ListUsersResponse struct that contains all of that.
use axum::{extract::Query, routing::get, Json, Router};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct Pagination {
page: Option<u32>,
limit: Option<u32>,
}
#[derive(Clone, Serialize)]
struct User {
id: u64,
name: String,
}
#[derive(Serialize)]
struct ListUsersResponse {
page: u32,
limit: u32,
total: usize,
users: Vec<User>,
}
async fn list_users(Query(pagination): Query<Pagination>) -> Json<ListUsersResponse> {
let page = pagination.page.unwrap_or(1);
let limit = pagination.limit.unwrap_or(10);
let all_users = vec![
User { id: 1, name: "Alice".to_string() },
User { id: 2, name: "Bob".to_string() },
User { id: 3, name: "Carol".to_string() },
User { id: 4, name: "Dave".to_string() },
User { id: 5, name: "Eve".to_string() },
User { id: 6, name: "Frank".to_string() },
User { id: 7, name: "Grace".to_string() },
User { id: 8, name: "Heidi".to_string() },
User { id: 9, name: "Ivan".to_string() },
User { id: 10, name: "Judy".to_string() },
];
let total = all_users.len();
let start = (page.saturating_sub(1) * limit) as usize;
let end = (start + limit as usize).min(total);
let users = if start >= total {
Vec::new()
} else {
all_users[start..end].to_vec()
};
Json(ListUsersResponse {
page,
limit,
total,
users,
})
}
Now the response looks like {"page":1,"limit":10,"total":10,"users":[...]}. Notice that we no longer return just Json<Vec<User>>; instead the outer type is Json<ListUsersResponse>, and ListUsersResponse contains the users as a field.
Total count requires extra data:
In this example total comes from the length of the hardcoded vector. In a real database-backed handler you would perform a SELECT COUNT(*) query or rely on your ORM to give you the total. Do not hardcode total unless you really only have a fixed set.
Making Defaults Part of the Struct
Repeating unwrap_or(1) and unwrap_or(10) inside every handler that uses Pagination becomes tedious. Serde provides an attribute called default that lets you specify a function to call when a field is missing. You can combine that with a helper function to set defaults directly during deserialization.
use axum::{extract::Query, routing::get, Json, Router};
use serde::{Deserialize, Serialize};
fn default_page() -> u32 {
1
}
fn default_limit() -> u32 {
10
}
#[derive(Deserialize)]
struct Pagination {
#[serde(default = "default_page")]
page: u32,
#[serde(default = "default_limit")]
limit: u32,
}
#[derive(Clone, Serialize)]
struct User {
id: u64,
name: String,
}
#[derive(Serialize)]
struct ListUsersResponse {
page: u32,
limit: u32,
users: Vec<User>,
}
async fn list_users(Query(pagination): Query<Pagination>) -> Json<ListUsersResponse> {
let page = pagination.page;
let limit = pagination.limit;
let all_users = vec![
User { id: 1, name: "Alice".to_string() },
User { id: 2, name: "Bob".to_string() },
User { id: 3, name: "Carol".to_string() },
User { id: 4, name: "Dave".to_string() },
User { id: 5, name: "Eve".to_string() },
];
let start = (page.saturating_sub(1) * limit) as usize;
let end = (start + limit as usize).min(all_users.len());
let users = if start >= all_users.len() {
Vec::new()
} else {
all_users[start..end].to_vec()
};
Json(ListUsersResponse { page, limit, users })
}
Now the Pagination struct always has concrete u32 values, and the handler code becomes slightly cleaner because there are no unwrap_or calls. The trade-off is that the struct definition is a little longer. This pattern is common when many handlers share the same pagination parameters.
Using serde defaults keeps your handler free of boilerplate:
If you expect several endpoints to accept page and limit, defining a reusable Pagination struct with serde(default = "...") will keep your handler bodies focused on business logic instead of repeated default-value bookkeeping.
Combining Pagination with an Optional Search Filter
A list_users handler often supports more than just pagination. A common addition is a search query parameter that filters users by name. You can add that field to the same struct, also optional.
use axum::{extract::Query, routing::get, Json, Router};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct ListUsersQuery {
page: Option<u32>,
limit: Option<u32>,
search: Option<String>,
}
#[derive(Clone, Serialize)]
struct User {
id: u64,
name: String,
}
#[derive(Serialize)]
struct ListUsersResponse {
page: u32,
limit: u32,
total: usize,
users: Vec<User>,
}
async fn list_users(Query(query): Query<ListUsersQuery>) -> Json<ListUsersResponse> {
let page = query.page.unwrap_or(1);
let limit = query.limit.unwrap_or(10);
let all_users = vec![
User { id: 1, name: "Alice".to_string() },
User { id: 2, name: "Bob".to_string() },
User { id: 3, name: "Carol".to_string() },
User { id: 4, name: "Charlie".to_string() },
User { id: 5, name: "Dave".to_string() },
User { id: 6, name: "Eve".to_string() },
User { id: 7, name: "Frank".to_string() },
User { id: 8, name: "Grace".to_string() },
];
let filtered_users: Vec<User> = match query.search {
Some(term) if !term.is_empty() => all_users
.into_iter()
.filter(|user| user.name.to_lowercase().contains(&term.to_lowercase()))
.collect(),
_ => all_users,
};
let total = filtered_users.len();
let start = (page.saturating_sub(1) * limit) as usize;
let end = (start + limit as usize).min(total);
let users = if start >= total {
Vec::new()
} else {
filtered_users[start..end].to_vec()
};
Json(ListUsersResponse {
page,
limit,
total,
users,
})
}
The new search field is an Option<String>. When it is None or an empty string, we treat it as no filter. When it has a value, we keep only users whose name contains the search term, case-insensitively. The pagination logic then applies to the filtered list, and total reflects the number of filtered users, not the original total.
Empty search strings can surprise you:
A query string like /users?search= will be parsed as Some("") because the parameter is present but empty. If you only check if let Some(term) = query.search, the empty string will be treated as a filter and likely return zero results. Always handle the empty-string case explicitly, as shown above.
Choosing Between Two Response Shapes
There are two dominant styles for returning paginated lists in JSON APIs. You have already seen one: an object that includes both metadata and the users array. The other style is to return just the array and let the client infer pagination from the URL and the number of items received. Both are valid, and the choice depends on your API design.
If your frontend needs to show "Page 2 of 10", the metadata object is more convenient because the backend sends total and page. If your frontend only needs to render a list and has no pagination controls, returning just the array reduces payload size and simplifies the handler.
The following two snippets show the same handler body adapted to each style.
Style A: Wrapper object with metadata
async fn list_users(Query(pagination): Query<Pagination>) -> Json<ListUsersResponse> {
// ... compute page, limit, total, users ...
Json(ListUsersResponse {
page,
limit,
total,
users,
})
}
Style B: Bare array
async fn list_users(Query(pagination): Query<Pagination>) -> Json<Vec<User>> {
// ... compute page, limit ...
// return only the slice, discarding total
Json(users)
}
There is no right or wrong answer universally. Many public APIs use the metadata wrapper because it gives clients more information with a single request, at the cost of a slightly larger response body. If you control both the frontend and backend, you can choose whichever makes the client code simpler.
A Complete Example with an In-Memory Store
Until now we have hardcoded the user list inside the handler. In a real application the data would come from somewhere else: a database, a cache, or another service. Let's move the user list into a shared application state using Arc and a Mutex so multiple requests can read it safely. This is a realistic pattern you will see often.
use axum::{
extract::{Query, State},
routing::get,
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};
#[derive(Clone)]
struct AppState {
users: Arc<Mutex<Vec<User>>>,
}
#[derive(Clone, Serialize)]
struct User {
id: u64,
name: String,
}
#[derive(Deserialize)]
struct Pagination {
page: Option<u32>,
limit: Option<u32>,
}
#[derive(Serialize)]
struct ListUsersResponse {
page: u32,
limit: u32,
total: usize,
users: Vec<User>,
}
async fn list_users(
State(state): State<AppState>,
Query(pagination): Query<Pagination>,
) -> Json<ListUsersResponse> {
let page = pagination.page.unwrap_or(1);
let limit = pagination.limit.unwrap_or(10);
let all_users = state.users.lock().unwrap().clone();
let total = all_users.len();
let start = (page.saturating_sub(1) * limit) as usize;
let end = (start + limit as usize).min(total);
let users = if start >= total {
Vec::new()
} else {
all_users[start..end].to_vec()
};
Json(ListUsersResponse {
page,
limit,
total,
users,
})
}
#[tokio::main]
async fn main() {
let users = vec![
User { id: 1, name: "Alice".to_string() },
User { id: 2, name: "Bob".to_string() },
User { id: 3, name: "Carol".to_string() },
User { id: 4, name: "Dave".to_string() },
User { id: 5, name: "Eve".to_string() },
User { id: 6, name: "Frank".to_string() },
User { id: 7, name: "Grace".to_string() },
User { id: 8, name: "Heidi".to_string() },
User { id: 9, name: "Ivan".to_string() },
User { id: 10, name: "Judy".to_string() },
];
let state = AppState {
users: Arc::new(Mutex::new(users)),
};
let app = Router::new()
.route("/users", get(list_users))
.with_state(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
In this version, the handler takes two extractors: State and Query. The order is important: non-body extractors like State must come before any body-consuming extractors. Since Query does not consume the body, it could come before or after State, but the convention is to put State first when you need it. The AppState struct holds an Arc<Mutex<Vec<User>>> so the handler can clone the whole vector without holding the lock for long.
Lock contention is real but fine for this example:
Using Mutex around a Vec<User> is simple but means only one request can read the user list at a time. For a read-only cache you could use Arc<Vec<User>> without a Mutex because immutable data can be shared safely across threads. The Mutex is shown here because in a real app the list might be updated while the server runs, and you need some synchronization.
Making Pagination Required (When It Makes Sense)
Although optional pagination with defaults is the most common design, some APIs require clients to send page and limit explicitly. You can do that by removing the Option wrapper and not providing Serde defaults. Then if either parameter is missing, the Query extractor will reject the request with a 400 error.
use axum::{extract::Query, routing::get, Json, Router};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct Pagination {
page: u32,
limit: u32,
}
#[derive(Serialize)]
struct User {
id: u64,
name: String,
}
async fn list_users(Query(pagination): Query<Pagination>) -> Json<Vec<User>> {
let page = pagination.page;
let limit = pagination.limit;
let all_users = vec![
User { id: 1, name: "Alice".to_string() },
User { id: 2, name: "Bob".to_string() },
User { id: 3, name: "Carol".to_string() },
];
let start = (page.saturating_sub(1) * limit) as usize;
let end = (start + limit as usize).min(all_users.len());
let users = if start >= all_users.len() {
Vec::new()
} else {
all_users[start..end].to_vec()
};
Json(users)
}
Now a request to /users without any query string fails, and the handler is never called. This is a stricter contract and can be appropriate if your API documentation explicitly states that pagination is mandatory. However, most public APIs prefer to be lenient and provide defaults.
Choose strictness based on your API contract:
If you are building an internal API where the frontend always sends pagination, making fields required can catch bugs early. If you are building a public API, optional parameters with defaults are friendlier to third-party developers who may not read your documentation carefully.
Handling Very Large Page Numbers
Even with correct parsing, a client could send page=99999, which would result in start being huge. The current slicing logic checks if start >= total and returns an empty array. That is safe, but you might want to return the last available page instead, or clamp the page to a maximum value. Which behavior is better depends on your API's expected semantics.
One common approach is to cap the page number at the total number of pages:
let total_pages = (total as u32).div_ceil(limit);
let page = page.min(total_pages.max(1));
This ensures that requesting an out-of-range page returns the last valid page instead of an empty list. Some clients prefer this, especially when they don't know the total page count in advance. Others prefer the empty-list behavior because it clearly signals that the requested page does not exist.
Clamping can hide client bugs:
If a client accidentally sends page=99999 due to a bug, clamping to the last page might silently return data and hide the error. Returning an empty list is often a clearer signal that something is wrong. Think about which behavior makes your API easier to debug before deciding.
Testing the Handler Without a Running Server
You can write unit tests for the list_users handler using tower::ServiceExt::oneshot. This tests the entire routing and extraction pipeline without binding a TCP port. It is especially useful for verifying that invalid query strings are rejected properly. tower is already in the Cargo.toml shown at the top of this page.
use axum::{body::Body, http::Request, Router};
use tower::ServiceExt;
#[tokio::test]
async fn test_list_users_with_default_pagination() {
let app = build_test_app();
let response = app
.oneshot(
Request::builder()
.uri("/users")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), axum::http::StatusCode::OK);
// Further assertions on the body can parse JSON here.
}
#[tokio::test]
async fn test_list_users_rejects_bad_page() {
let app = build_test_app();
let response = app
.oneshot(
Request::builder()
.uri("/users?page=abc")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), axum::http::StatusCode::BAD_REQUEST);
}
The build_test_app function would return a Router with the same routes and state as production. Here is one for the handler from this page, using the plain Query version of list_users:
use axum::{extract::Query, routing::get, Json, Router};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct Pagination {
page: Option<u32>,
limit: Option<u32>,
}
#[derive(Clone, Serialize)]
struct User {
id: u64,
name: String,
}
async fn list_users(Query(pagination): Query<Pagination>) -> Json<Vec<User>> {
let page = pagination.page.unwrap_or(1);
let limit = pagination.limit.unwrap_or(10);
let all_users = vec![
User { id: 1, name: "Alice".to_string() },
User { id: 2, name: "Bob".to_string() },
User { id: 3, name: "Carol".to_string() },
];
let start = (page.saturating_sub(1) * limit) as usize;
let end = (start + limit as usize).min(all_users.len());
let users = if start >= all_users.len() {
Vec::new()
} else {
all_users[start..end].to_vec()
};
Json(users)
}
fn build_test_app() -> Router {
Router::new().route("/users", get(list_users))
}
Testing handlers in isolation like this is fast and catches mistakes in query parameter handling early.
Common Mistakes and How to Avoid Them
- Forgetting
serde(default = "...")when you want defaults but notOption. This leads to a400error for missing parameters even though you intended defaults. - Assuming
pageandlimitareu32when they can be negative. Query parameters are strings; Serde will reject-1if the target is unsigned. Consider usingi32if you want to accept and then validate range manually. - Not handling empty strings for
Stringquery parameters./users?search=producesSome(""), which is often not what you expect. - Using
unwrap_orinside the handler repeatedly instead of moving defaults to the struct. This clutters the handler and makes it harder to change defaults later. - Ignoring the
totalcount when filtering. If you paginate a filtered list, thetotalshould reflect the number of filtered items, not the original set.
The most consequential beginner mistake:
The number one error is treating Option<u32> fields as always Some and calling .unwrap() on them. This panics the request if the parameter is missing. Always use unwrap_or, unwrap_or_default, or serde(default = "...") to provide fallbacks.
Summary
This page walked through building a realistic list_users handler that uses the Query extractor for pagination and optional filtering. You started with a handler that returned a hardcoded JSON array, then progressively added optional page and limit parameters, defaults via Serde, a metadata wrapper, search filtering, and shared in-memory state. Along the way you saw how to handle rejections with Result<Query<T>, QueryRejection>, how to choose between response shapes, and how to test the handler without a live server.
The central idea is that the Query extractor turns the messy query string into a typed, deserialized struct, and your handler can then focus on business logic like slicing a user list. Once you master this pattern, you can apply it to any list endpoint in your application - items, posts, transactions, or anything else that benefits from pagination and filtering.
The design choices on this page reduce to three questions. First, must the client always send page and limit, or should the endpoint work with none at all? Defaults win for public list endpoints; required fields only fit an internal API where the caller always sends them. Second, does the client need to know how many items exist in total? If it renders page controls, return a wrapper object with total; if it only renders a list, a bare array is enough. Third, should a bad query string produce Axum's plain text 400, or your own JSON error? If your API promises JSON everywhere, wrap the extractor in Result<Query<T>, QueryRejection> from the start, because the default error shape is the one thing you cannot change after the fact.