FAQ - Help and questions

How do I read query string parameters in axum, with defaults and optional values?

#axum#query-string#serde#extractorspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Add the Query extractor to the handler and give it a struct that derives Deserialize. Optional parameters are Option fields, a default comes from #[serde(default = "...")], and a missing required field or a value of the wrong type produces a 400 response before your handler runs.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, tower 0.5.3, Windows 11; handlers called in-process with tower's oneshot

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

src/main.rsrust
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:

text
/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 string
  • q has no default and no Option, so it is required.
  • page falls back to 1 through serde(default = ...).
  • tag is 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, as tag and page do 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.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet