Query Extractor
Learn how to extract query string parameters from request URLs in Axum using the Query extractor, with typed structs, optional fields, and error handling.
Query parameters are the part of a URL that comes after the question mark. They look like ?page=2&sort=name and let clients send small pieces of data to a server without putting them in the URL path. In Axum, the Query extractor takes those parameters and turns them into a Rust value your handler can use.
What Query Parameters Are For
When a user searches for products on an e-commerce site, the URL might look like /products?category=books&page=2&sort=price. The path is /products, and everything after ? is the query string. Each key=value pair is separated by &, and the entire string is called the query string.
Query parameters are perfect for optional, non-hierarchical data. They don't identify a specific resource the way path segments do; instead they refine a request. Common real-world uses include:
- Pagination:
?page=3&limit=20 - Search filters:
?category=electronics&brand=apple - Sorting:
?sort=price&order=desc - Search terms:
?q=rust+web+framework
Because they are so common, Axum provides a dedicated extractor called Query to parse them safely.
How the Query Extractor Works
The Query extractor is a type that implements FromRequestParts. That means it can run before your handler and produce a value based on the request's URL, without reading the request body. You use it by writing Query(something) as an argument to your handler, where something is the target type you want the query string to be parsed into.
The extractor automatically percent-decodes the query string and splits it into keys and values. Then it attempts to deserialize those pairs into the type you requested. If the type is a HashMap<String, String>, you get a map of all parameters. If the type is a struct that derives serde::Deserialize, Axum will match keys to struct fields and convert values to the correct Rust types.
Feature flag required:
The Query extractor is part of Axum's default features, but if you are using a minimal setup with default-features = false, you must enable the query feature in your Cargo.toml.
Basic Example with HashMap
Start with the simplest possible extraction: capturing every query parameter as a HashMap<String, String>. This gives you complete flexibility because you can access any key at runtime, but it also means you must manually convert values to the types you need.
Here is a complete Axum application that returns a list of all query parameters sent to the /search route:
// Cargo.toml
[package]
name = "query-basic"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
// src/main.rs
use axum::{extract::Query, routing::get, Router};
use std::collections::HashMap;
async fn search_handler(Query(params): Query<HashMap<String, String>>) -> String {
let mut output = String::from("Query parameters:\n");
for (key, value) in ¶ms {
output.push_str(&format!(" {} = {}\n", key, value));
}
output
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/search", get(search_handler));
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();
}
Run the server and open http://127.0.0.1:3000/search?page=2&sort=name. You will see:
Query parameters:
page = 2
sort = name
What happened behind the scenes? Axum took the raw query string page=2&sort=name, percent-decoded it, split it at the & into two pairs, split each pair at the =, and inserted them into the HashMap. The handler then iterated over the map and printed each key and value.
Using a HashMap is handy when you don't know the parameter names ahead of time or when you want to pass them through without interpretation. But in most applications you know exactly which keys to expect, and you want type safety.
Typed Query with a Struct
A much more common pattern is to define a struct that represents the expected query parameters and derive serde::Deserialize on it. Axum will then attempt to convert each parameter to the declared field type. If a parameter is missing or has the wrong type, Axum rejects the request with a 400 Bad Request response before your handler runs.
Let's build a pagination-aware search endpoint:
// src/main.rs
use axum::{extract::Query, routing::get, Router};
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct SearchParams {
page: u32,
limit: u32,
sort: String,
}
async fn search_handler(Query(params): Query<SearchParams>) -> String {
format!(
"Page: {}, Limit: {}, Sort by: {}",
params.page, params.limit, params.sort
)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/search", get(search_handler));
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();
}
Now request http://127.0.0.1:3000/search?page=1&limit=20&sort=price. The response body will be:
Page: 1, Limit: 20, Sort by: price
Notice how page and limit are parsed as u32 automatically. If you send ?page=abc, Axum cannot parse abc into a u32 and will return an error response. This is a huge advantage over manually parsing strings: incorrect input is rejected early, and your handler only runs with valid data.
Correct setup:
If you see the exact output above and no errors in the terminal, your Query extractor is working correctly with a typed struct.
Optional Query Parameters
Not every query parameter is required. A search endpoint might allow ?sort=price but also work without any sort at all. In Rust, you represent an optional value with Option<T>. If the parameter is missing from the query string, Axum sets the field to None. If it is present, you get Some(value).
Modify the previous struct to make sort optional, and add a min_price optional field:
#[derive(Debug, Deserialize)]
struct SearchParams {
page: u32,
limit: u32,
sort: Option<String>,
min_price: Option<f64>,
}
async fn search_handler(Query(params): Query<SearchParams>) -> String {
let sort = params.sort.as_deref().unwrap_or("relevance");
let min_price = params.min_price.unwrap_or(0.0);
format!(
"Page: {}, Limit: {}, Sort by: {}, Min price: {}",
params.page, params.limit, sort, min_price
)
}
Now these requests all succeed:
/search?page=1&limit=10→sortisNone,min_priceisNone/search?page=1&limit=10&sort=price→sortisSome("price")/search?page=1&limit=10&sort=price&min_price=99.99→ both present
The handler uses unwrap_or to provide sensible defaults when a parameter is absent. This keeps the handler logic clean.
Empty string is not missing:
A query string like ?sort= sends an empty string, not None. Axum will parse it as Some("") for an Option<String>. If you want to treat empty strings as missing, you need to handle that in your handler logic.
Handling Multiple Values for the Same Key
Sometimes clients send the same query parameter multiple times, like ?tag=rust&tag=web&tag=axum. Axum's built-in Query extractor cannot handle this: it uses serde_urlencoded, which rejects a repeated key when the target is a sequence, returning a 400 Bad Request with body Failed to deserialize query string: tag: invalid type: string "rust", expected a sequence . For repeated keys you need the Query extractor from axum-extra, which uses serde_html_form and supports multi-value items. Enable its query feature:
[dependencies]
axum-extra = { version = "0.12", features = ["query"] }
Then use axum_extra::extract::Query instead of axum::extract::Query:
use axum::{routing::get, Router};
use axum_extra::extract::Query;
use std::collections::HashMap;
async fn tags_handler(Query(params): Query<HashMap<String, Vec<String>>>) -> String {
match params.get("tag") {
Some(tags) => format!("Tags: {}", tags.join(", ")),
None => "No tags provided".to_string(),
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/tags", get(tags_handler));
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();
}
Request http://127.0.0.1:3000/tags?tag=rust&tag=web&tag=axum. The response is:
Tags: rust, web, axum
If you use a struct with a field of type Vec<String>, axum-extra's Query will also collect repeated values into that field. Here is the same endpoint written with a struct, so the field name is checked at compile time:
use axum::{routing::get, Router};
use axum_extra::extract::Query;
use serde::Deserialize;
#[derive(Deserialize)]
struct TagParams {
tag: Vec<String>,
}
async fn tags_handler(Query(params): Query<TagParams>) -> String {
if params.tag.is_empty() {
"No tags provided".to_string()
} else {
format!("Tags: {}", params.tag.join(", "))
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/tags", get(tags_handler));
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();
}
A request to /tags?tag=rust&tag=web&tag=axum gives the same Tags: rust, web, axum response. Both approaches work with axum_extra::extract::Query; the HashMap<String, Vec<String>> is more dynamic, while the struct gives you compile-time knowledge of the field name.
Error Handling with Result and QueryRejection
Sometimes you want to handle a query parsing error yourself instead of letting Axum return a generic 400 Bad Request. You can do that by wrapping the Query extractor in a Result, using QueryRejection as the error type.
use axum::{
extract::{Query, rejection::QueryRejection},
http::StatusCode,
response::{IntoResponse, Response},
routing::get,
Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct Pagination {
page: u32,
}
async fn paginated_handler(
result: Result<Query<Pagination>, QueryRejection>,
) -> Response {
match result {
Ok(Query(params)) => {
format!("Showing page {}", params.page).into_response()
}
Err(rejection) => {
// You can inspect the rejection to give a custom message.
let message = format!("Failed to parse query: {}", rejection.body_text());
(StatusCode::BAD_REQUEST, message).into_response()
}
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/items", get(paginated_handler));
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();
}
When a request with ?page=abc arrives, the handler receives an Err(QueryRejection::FailedToDeserializeQueryString(...)). The code extracts the inner error message and returns a custom response. This gives you full control over error formatting, logging, or fallback behavior.
Missing Deserialize derive:
If you forget to add #[derive(Deserialize)] to your struct, the compiler will produce an error saying that the type does not implement Deserialize. This is the most common mistake when first using Query with a struct. Always check that your struct derives serde::Deserialize.
Combining Query with Other Extractors
You can use Query alongside other extractors like Path, State, or HeaderMap. The order matters only when a body-consuming extractor is involved; Query never consumes the body, so it can appear anywhere in the argument list.
use axum::{
extract::{Path, Query, State},
routing::get,
Router,
};
use std::collections::HashMap;
#[derive(Clone)]
struct AppState {
default_limit: u32,
}
async fn list_products(
Path(category): Path<String>,
Query(params): Query<HashMap<String, String>>,
State(state): State<AppState>,
) -> String {
let limit = params
.get("limit")
.and_then(|v| v.parse::<u32>().ok())
.unwrap_or(state.default_limit);
format!("Listing {} products, limit {}", category, limit)
}
#[tokio::main]
async fn main() {
let state = AppState { default_limit: 10 };
let app = Router::new()
.route("/products/{category}", get(list_products))
.with_state(state);
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();
}
This example extracts the category from the URL path, the query parameters as a map, and shared application state. The handler then decides which limit to use: the one from the query string if present and parseable, otherwise the state's default.
Common Mistakes and Misconceptions
Assuming Query reads the request body. It does not. It only parses the URL query string. If you need to read form data or JSON from the body, you must use other extractors.
Thinking missing required parameters return None. If your struct field is not Option<T> and the parameter is absent, Axum returns a 400 Bad Request. It does not silently fill in 0 or an empty string. Use Option<T> for optional fields.
Trying to parse a query string with multiple values into a scalar field. If the client sends ?id=1&id=2 and your struct has id: u32, Axum returns a 400 Bad Request with body Failed to deserialize query string: duplicate field `id` , because it cannot fit two values into one. Use axum_extra::extract::Query with a Vec<T> field if you expect repeats.
Forgetting to enable the query feature flag when using a minimal Cargo setup. Without it, Query is not available and the import will fail. With default features on, the flag is already enabled, so this only bites when you set default-features = false.
Summary
The Query extractor is how Axum hands you the query string from a request URL in a structured, type-safe way. You can capture parameters as a flexible HashMap, or define a struct that mirrors the expected keys and lets serde handle conversion and validation. Optional parameters become Option<T>, repeated keys need axum_extra::extract::Query to map to vectors (the built-in Query rejects them), and errors are easy to customize with Result<Query<T>, QueryRejection>.
Once you are comfortable extracting query parameters, the natural next step is understanding how to enable or disable the query feature flag in your Cargo configuration, which controls whether this extractor is compiled into your application at all.