Serde Query Structs in Axum
Learn how to deserialize query parameters into typed Rust structs using serde and the Query extractor in Axum
When you build a web API, incoming requests often carry extra data in the URL after a question mark. For example, /search?term=rust&limit=10. These key-value pairs are called query parameters. Axum provides a way to grab all of them at once and turn them into a Rust struct you define. That struct can then have named fields with real types like String, u32, or bool, instead of you manually parsing strings from a generic map.
This page explains how to define such structs using serde (the most common serialization and deserialization library in Rust) and use them with Axum's Query extractor. A query string can also be read as a plain map of strings, but a struct describes exactly what parameters your handler expects, with real types for each one.
Why Use a Struct Instead of a HashMap
A HashMap<String, String> gives you all query parameters as strings, but you have to manually get each value and convert it to the type you actually need. For example, to read a numeric limit, you would write something like params.get("limit").and_then(|v| v.parse().ok()). That is verbose, error-prone, and scattered across your handler. A struct with typed fields moves all that parsing and validation into one place and makes your handler code much cleaner.
With a serde struct, Axum automatically parses each query parameter into the field's type. If a parameter is missing or has the wrong format, Axum returns a 400 Bad Request response to the client before your handler even runs. You get type safety without writing any manual parsing code.
Setting Up Dependencies
To use serde query structs, your Cargo.toml needs two things, plus a third crate only for the repeated-keys example later on this page:
- Axum with the
queryfeature enabled. This feature is enabled by default, so a plainaxum = "0.8"dependency already includes it. You only need to list it explicitly if you disabled default features:
axum = { version = "0.8", features = ["query"] }
- Serde with the
derivefeature. This gives you the#[derive(Deserialize)]attribute. Add serde as a dependency:
serde = { version = "1.0", features = ["derive"] }
- The
axum-extracrate, only if you need repeated keys. TheVec<T>example below usesaxum_extra::extract::Query, which collects repeated query keys into a list. That extractor lives in a separate crate, so add it with itsqueryfeature:
axum-extra = { version = "0.12", features = ["query"] }
You do not need axum-extra for the other examples on this page. Axum's built-in Query handles every other case shown here.
Now create a new binary project or continue in your existing Axum project. In this page's examples we assume a typical main.rs file with a main function that builds a router and starts the server.
A First Basic Example
Let's start with the absolute minimum. You have a route like /hello and you want to read two query parameters: name (a string) and age (an unsigned integer). The URL might look like /hello?name=Alice&age=30.
Define a struct that mirrors those parameters:
use axum::extract::Query;
use serde::Deserialize;
#[derive(Deserialize)]
struct HelloParams {
name: String,
age: u32,
}
async fn hello(Query(params): Query<HelloParams>) -> String {
format!("Hello, {}! You are {} years old.", params.name, params.age)
}
The #[derive(Deserialize)] line tells serde to generate code that can turn a sequence of key-value pairs (like query parameters) into this struct. The Query<HelloParams> extractor then uses that generated code when Axum receives a request.
Now register the handler with a router in main:
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/hello", get(hello));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Run the program and open http://127.0.0.1:3000/hello?name=Alice&age=30 in a browser or use curl. You will see:
Hello, Alice! You are 30 years old.
If you omit age (e.g., /hello?name=Bob), Axum will not call your handler. Instead it will respond with a 400 Bad Request and an error message saying Failed to deserialize query string: missing field `age` . Similarly, if you pass age=thirty, the response is 400 because thirty is not a valid u32.
Everything Works:
If you see the correct greeting and a 400 response for missing or invalid fields, your struct extraction is working correctly.
How Serde Maps Query Parameters to Fields
Serde treats query parameters as a sequence of key-value pairs. By default, each struct field name is matched against a query parameter name exactly. Matching is case-sensitive. So a field named name expects a query parameter name, not Name or NAME.
When Axum receives the query string name=Alice&age=30, it splits it on & to get name=Alice and age=30, then splits each on = to get key and value. These pairs are handed to serde, which matches keys to struct fields.
If the query string contains a parameter that does not correspond to any struct field, serde ignores it by default. For example, /hello?name=Alice&age=30&extra=abc works fine; extra is silently dropped. This can be useful when clients send extra data, but be aware of it.
Handling Different Types
A struct is not limited to String and u32. Serde supports many Rust types out of the box, as long as the value string can be converted to that type. Common ones include:
String- any textu32,i32,u64,i64,usize, etc. - integersf32,f64- floating-point numbersbool-trueorfalseOption<T>- allows the field to be optional, so a missing parameter becomesNoneinstead of an errorVec<T>- a list of values from repeated query parameters, liketag=rust&tag=axum, but only with theQueryextractor fromaxum-extra, not with Axum's built-inQuery
Here is an example with several types. Note the import: repeated keys are rejected by Axum's built-in Query (it returns a 400 Bad Request), so this example uses axum_extra::extract::Query with the query feature of axum-extra enabled:
use axum_extra::extract::Query as ExtraQuery;
use serde::Deserialize;
#[derive(Deserialize)]
struct FilterParams {
query: String,
page: u32,
active: bool,
tags: Vec<String>,
}
async fn filter(ExtraQuery(params): ExtraQuery<FilterParams>) -> String {
format!(
"Searching for '{}', page {}, active={}, tags={:?}",
params.query, params.page, params.active, params.tags
)
}
A valid request could be:
/filter?query=axum&page=2&active=true&tags=rust&tags=web
This would produce:
Searching for 'axum', page 2, active=true, tags=["rust", "web"]
Notice how multiple tags parameters are collected into a Vec<String>. The axum-extra extractor accumulates repeated keys when the target type is a Vec; Axum's built-in Query does not support this and rejects repeated keys.
Boolean Values Are Strict:
The bool type accepts only the exact lowercase strings true and false. Values like True, 1, or yes will cause a 400 Bad Request.
Renaming Fields with #[serde(rename)]
Sometimes the query parameter names you want to support are not valid Rust identifiers or you prefer different names in your code. For example, a query parameter might be search-term but you cannot have a struct field named search-term because hyphens are not allowed in Rust identifiers. Serde provides the rename attribute for this.
use axum::extract::Query;
use serde::Deserialize;
#[derive(Deserialize)]
struct SearchParams {
#[serde(rename = "search-term")]
search_term: String,
#[serde(rename = "max")]
limit: u32,
}
async fn search(Query(params): Query<SearchParams>) -> String {
format!(
"Looking for '{}' with limit {}",
params.search_term, params.limit
)
}
Now the URL /search?search-term=rust&max=20 works. The field in your Rust code is still search_term and limit, but the wire format uses search-term and max.
Providing Default Values
By default, every field in a serde struct is required. If a query parameter for a required field is missing, Axum returns a 400 error. But sometimes you want a field to have a fallback value when the parameter is absent. You can achieve this with #[serde(default)].
#[serde(default)] can be used in two ways:
- Without a value - if the field is missing, use the type's
Default::default()(foru32that is0, forStringthat is an empty string, forboolit isfalse, etc.). - With a function - you can provide a custom function to compute the default value.
Here is an example using the simple #[serde(default)]:
use axum::extract::Query;
use serde::Deserialize;
#[derive(Deserialize)]
struct Pagination {
page: u32,
#[serde(default)]
per_page: u32,
}
async fn list_items(Query(params): Query<Pagination>) -> String {
format!("Page {}, showing {} items per page", params.page, params.per_page)
}
If the client visits /items?page=1, per_page is missing, so it defaults to 0. That is probably not ideal for a real pagination API, but it shows the behavior. If you want a more meaningful default, use a custom function:
fn default_per_page() -> u32 {
10
}
#[derive(Deserialize)]
struct Pagination {
page: u32,
#[serde(default = "default_per_page")]
per_page: u32,
}
Now /items?page=1 results in per_page being 10. Note the function name is passed as a string to default.
Option fields are a different choice:
The Option<T> type also allows missing parameters, but it behaves differently: None instead of a default. Use it when the handler needs to know that a parameter was absent, rather than just receiving a fallback value.
Nested Structs
Axum's built-in Query extractor does not support nested structs. The query string is a flat list of key-value pairs, and serde_urlencoded, which the extractor uses, has no way to group keys into a nested struct. Dot notation does not work: a request like /route?user.name=Alice&user.age=30&verbose=true fails with a 400 Bad Request and body Failed to deserialize query string: missing field `user` , because the key user.name does not match the field user. #[serde(flatten)] does not fix this either; it fails as well.
use axum::extract::Query;
use serde::Deserialize;
#[derive(Deserialize)]
struct User {
name: String,
age: u32,
}
#[derive(Deserialize)]
struct Request {
user: User,
verbose: bool,
}
async fn handle(Query(params): Query<Request>) -> String {
format!(
"User {} is {} years old. Verbose: {}",
params.user.name, params.user.age, params.verbose
)
}
The struct above compiles, but no query string will deserialize into it with the built-in Query extractor. Keep query structs flat: put every parameter in one struct with a field per key, for example user_name and user_age as top-level fields. If you genuinely need nesting, parse the query string yourself or use a different extractor.
Complete Working Example
Let's put everything together into one runnable program that shows a few routes with different structs. Create a new Rust project and replace main.rs with the following:
use axum::{extract::Query, routing::get, Router};
use axum_extra::extract::Query as ExtraQuery;
use serde::Deserialize;
#[derive(Deserialize)]
struct HelloParams {
name: String,
age: u32,
}
#[derive(Deserialize)]
struct FilterParams {
query: String,
page: u32,
active: bool,
tags: Vec<String>,
}
#[derive(Deserialize)]
struct SearchParams {
#[serde(rename = "search-term")]
search_term: String,
#[serde(rename = "max")]
limit: u32,
}
fn default_per_page() -> u32 {
10
}
#[derive(Deserialize)]
struct Pagination {
page: u32,
#[serde(default = "default_per_page")]
per_page: u32,
}
async fn hello(Query(params): Query<HelloParams>) -> String {
format!("Hello, {}! You are {} years old.", params.name, params.age)
}
async fn filter(ExtraQuery(params): ExtraQuery<FilterParams>) -> String {
format!(
"Searching for '{}', page {}, active={}, tags={:?}",
params.query, params.page, params.active, params.tags
)
}
async fn search(Query(params): Query<SearchParams>) -> String {
format!(
"Looking for '{}' with limit {}",
params.search_term, params.limit
)
}
async fn list_items(Query(params): Query<Pagination>) -> String {
format!("Page {}, showing {} items per page", params.page, params.per_page)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/hello", get(hello))
.route("/filter", get(filter))
.route("/search", get(search))
.route("/items", get(list_items));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The /filter route uses axum_extra::extract::Query (with the query feature of axum-extra enabled) because only it collects repeated tags parameters into a Vec; the built-in Query would reject them. The other routes use Axum's built-in Query.
Run cargo run and try the following URLs:
http://127.0.0.1:3000/hello?name=Alice&age=30http://127.0.0.1:3000/filter?query=axum&page=2&active=true&tags=rust&tags=webhttp://127.0.0.1:3000/search?search-term=rust&max=20http://127.0.0.1:3000/items?page=3
Each route shows how a different struct shape handles its query parameters.
Missing Field Causes 400:
Always remember that by default all fields are required. If a client forgets a parameter, the request will be rejected with a 400 Bad Request. Use #[serde(default)] or Option<T> when a parameter should be optional.
Comparing with Manual Extraction
Before structs, you might have extracted query parameters using Query<HashMap<String, String>> and then parsed each value by hand. Let's compare the two approaches for a simple case.
Manual approach:
use axum::extract::Query;
use std::collections::HashMap;
async fn old_style(Query(params): Query<HashMap<String, String>>) -> String {
let name = params.get("name").cloned().unwrap_or_default();
let age = params
.get("age")
.and_then(|v| v.parse::<u32>().ok())
.unwrap_or(0);
format!("Hello, {}! You are {} years old.", name, age)
}
Struct approach:
use axum::extract::Query;
use serde::Deserialize;
#[derive(Deserialize)]
struct HelloParams {
name: String,
age: u32,
}
async fn new_style(Query(params): Query<HelloParams>) -> String {
format!("Hello, {}! You are {} years old.", params.name, params.age)
}
The struct version is shorter, expresses the intended shape of the query directly, and automatically returns a 400 error if age is missing or not a number. The manual version silently uses a default value, which might hide bugs. For most production code, the struct approach is preferred.
Common Mistakes and How to Avoid Them
- Forgetting to enable the
queryfeature. Thequeryfeature is on by default, so this only happens withdefault-features = false. If you get an error likecould not find Query in extract, check that yourCargo.tomlhasaxum = { version = "...", features = ["query"] }. - Forgetting
#[derive(Deserialize)]. If you omit this attribute, Axum cannot deserialize the struct and you will get a compile-time error about missingDeserializeimplementation. - Mismatched field names. Rust is case-sensitive. If your struct has
userName(camelCase) but the query parameter isusername(lowercase), serde will not match them. Use#[serde(rename = "username")]on the field to fix it. - Assuming query parameters are ordered. Serde does not care about the order of parameters in the URL.
/hello?age=30&name=Aliceis treated the same as/hello?name=Alice&age=30. - Expecting automatic conversion of unconventional formats. For example,
boolonly acceptstrue/false; withaxum_extra::extract::Query,Vec<T>accumulates repeated keys, not comma-separated values. If your client sendstags=rust,axumyou will get a single string"rust,axum"as one element of the vector. If you need comma-separated parsing, you'll need a custom deserializer. With Axum's built-inQuery, repeated keys are rejected outright. - Using
#[serde(default)]on aStringfield and expecting a non-empty default. The default forStringis an empty string. Provide a custom function if you need something else.
Serde Errors Are Client Errors:
When serde cannot parse a query parameter, Axum responds with 400 Bad Request. This is correct because the client sent invalid data. Do not try to catch this in your handler; it happens before your handler is called.
Summary
Serde query structs give you a clean, type-safe way to handle URL query parameters in Axum. Instead of dealing with raw strings or hash maps, you define a Rust struct with fields that mirror the expected parameters, derive Deserialize, and let Axum do the parsing. This centralizes parsing logic, improves code readability, and automatically returns a 400 response for malformed input.
The decision framework is short. Use a struct when the parameter names are known in advance, which is almost always: it documents the API and rejects bad input before your handler runs. Use a HashMap only when the keys are genuinely dynamic and cannot be listed ahead of time. Reach for axum-extra only when you need repeated keys collected into a Vec. And keep the struct flat: a query string is a flat list of pairs, so a nested struct has no way to receive its data, and #[serde(flatten)] does not rescue it. When a parameter may be absent, the choice between Option<T> and #[serde(default)] comes down to one question: does your handler need to know the parameter was missing? If yes, use Option<T> and see None. If no, use a default and always work with a concrete value.