Answer#
Query<T> deserializes the part of the URL after ? into T. Missing required fields and wrong types are rejected with 400 Bad Request and the handler is never called.
use axum::{body::{to_bytes, Body}, extract::Query, http::Request, routing::get, Router};
use serde::Deserialize;
use tower::ServiceExt;
#[derive(Debug, Deserialize)]
#[allow(dead_code)] // the fields are only read through Debug here
struct Search {
q: String,
#[serde(default = "default_page")]
page: u32,
tag: Option<String>,
}
fn default_page() -> u32 { 1 }
async fn search(Query(s): Query<Search>) -> String { format!("{s:?}") }
#[tokio::main]
async fn main() {
let app = Router::new().route("/search", get(search));
for uri in ["/search?q=rust", "/search?q=rust&page=3&tag=web", "/search?q=a%20b", "/search", "/search?q=x&page=two"] {
let res = app.clone().oneshot(Request::get(uri).body(Body::empty()).unwrap()).await.unwrap();
let status = res.status().as_u16();
let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
println!("{uri} -> {status} {}", String::from_utf8_lossy(&body));
}
}Output:
/search?q=rust -> 200 Search { q: "rust", page: 1, tag: None }
/search?q=rust&page=3&tag=web -> 200 Search { q: "rust", page: 3, tag: Some("web") }
/search?q=a%20b -> 200 Search { q: "a b", page: 1, tag: None }
/search -> 400 Failed to deserialize query string: missing field `q`
/search?q=x&page=two -> 400 Failed to deserialize query string: page: invalid digit found in stringqhas no default and noOption, so it is required.pagefalls back to1throughserde(default = ...).tagis optional.- Percent-encoding (
a%20b) is decoded for you.
Common mistakes#
- Making every field required for a page that also works without parameters. Use
Option<T>or a serde default, astagandpagedo above. - Reading the 400 text as a server bug. It names the missing field or the value that did not parse (see the last two lines of the output), which is what the caller needs to fix.
Related questions#
How do I turn the 400 text into JSON?#
Wrap the extractor in your own type or handle the rejection; the thread on error responses shows a consistent error shape.
Is a query string the right place for a password?#
No. URLs end up in logs and browser history. Use a POST body.
Sources#
- axum,
Query: https://docs.rs/axum/0.8.9/axum/extract/struct.Query.html (read 2026-12-05) - serde field attributes: https://serde.rs/field-attrs.html