expression

Axum: typed query parameters

Query decodes the query string into a deserializable structure. Option allows an omitted value, but a malformed supplied value can still cause rejection. Apply application bounds after parsing. In-memory standalone Cargo example. No socket is opened. Expected stdout (not executed): 10 100 status 400 Common mistake: Treating successful integer parsing as a safe pagination limit.

Formal Syntax & Structure

rust syntaxrust
Query(params): Query<Params>

Working Example

Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    use axum::{extract::Query, routing::get};    #[derive(serde::Deserialize)]    struct Params { limit: Option<u16> }    async fn list(Query(p): Query<Params>) -> String { p.limit.unwrap_or(10).min(100).to_string() }    let app = Router::new().route("/items", get(list));    for uri in ["/items", "/items?limit=999", "/items?limit=no"] {        let r = app.clone().oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap()).await.unwrap();        if r.status().is_success() { println!("{}", std::str::from_utf8(&to_bytes(r.into_body(), 32).await.unwrap()).unwrap()); }        else { println!("status {}", r.status().as_u16()); }    }}
Rust Reference