Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 38 ยท Extractors and Responses

Path and Query Extractors in Axum

Read query strings in Axum with Query<T>: optional filters, defaults with serde, pagination limits, repeated keys, percent-decoding, and combining Path with Query.

Chapter 2 gave you routes and handlers. Chapter 3 is about the arguments of handlers: extractors. An extractor is a type that knows how to build itself from an incoming request. You already used Path<T> for URL captures. This lesson adds Query<T> for the query string (?page=2&sort=name) and shows how the two combine.

Query strings carry the optional parts of a request: filters, sorting, paging, flags. Captures identify which resource; the query shapes how you want it. Keeping them apart gives you URLs like /users/42/posts?status=draft&limit=20.

How extractors work (the short version)

Every extractor implements FromRequestParts (it only reads the head of the request: method, URI, headers) or FromRequest (it consumes the body too). A handler may have any number of the first kind, and at most one of the second kind, which must be the last argument. Path and Query are of the first kind, so their order does not matter. The handler lesson explains why the body extractor must come last.

If extraction fails, Axum does not call your handler. It answers with the extractor's rejection, normally a 400. Later in this chapter you will customise rejections.

Query<T>

Query<T> deserialises the query string with serde_urlencoded into any T: Deserialize:

Rust
use axum::{extract::Query, routing::get, Router};
use serde::Deserialize;

#[derive(Deserialize)]
struct Filters {
    q: Option<String>,
    role: Option<String>,
    active: Option<bool>,
}

async fn list_users(Query(f): Query<Filters>) -> String {
    format!("q={:?} role={:?} active={:?}", f.q, f.role, f.active)
}

fn app() -> Router {
    Router::new().route("/users", get(list_users))
}
Request Result
/users all three are None
/users?q=ana&active=true q = Some("ana"), active = Some(true)
/users?active=maybe 400 Bad Request, handler not run
/users?unknown=1 fine: unknown keys are ignored

Rules to remember:

  • A field of type Option<T> is optional. A plain T is required: leaving it out gives a 400.
  • Unknown keys are ignored unless you add #[serde(deny_unknown_fields)].
  • Values are percent-decoded and + becomes a space, so ?q=hello+world and ?q=hello%20world both give "hello world".
  • Everything arrives as a string first. Numbers and booleans are parsed from text, so ?page=2 works for u32.

Defaults with serde

Use #[serde(default)] for fields with a sensible fallback, so the client can leave them out:

Rust
#[derive(Deserialize)]
struct Page {
    #[serde(default = "default_page")]
    page: u32,
    #[serde(default = "default_limit")]
    limit: u32,
}

fn default_page() -> u32 { 1 }
fn default_limit() -> u32 { 20 }

Or derive Default on the whole struct and put #[serde(default)] on the struct itself.

Clamp before you trust

A query string is user input. ?limit=1000000 will happily parse as a u32. Clamp inside the handler (or in a small constructor) so one request cannot ask your database for everything:

Rust
let limit = page.limit.clamp(1, 100);
let offset = (page.page.max(1) - 1) * limit;

Repeated keys and lists

serde_urlencoded does not turn ?tag=a&tag=b into a Vec. Three common solutions:

  1. Use a comma-separated value (?tags=a,b) and split it yourself, or with #[serde(deserialize_with = ...)].
  2. Use axum_extra::extract::Query, which supports repeated keys and Vec<T> fields.
  3. Take RawQuery (the unparsed string) or Query<Vec<(String, String)>> and group the pairs.

Dynamic keys

When you cannot know the keys in advance, take a map:

Rust
use std::collections::HashMap;

async fn debug(Query(params): Query<HashMap<String, String>>) -> String {
    format!("{} parameters", params.len())
}

Combining Path and Query

Rust
use axum::extract::{Path, Query};

#[derive(Deserialize)]
struct PostFilter {
    status: Option<String>,
    #[serde(default = "default_limit")]
    limit: u32,
}

async fn user_posts(
    Path(user_id): Path<u64>,
    Query(filter): Query<PostFilter>,
) -> String {
    format!("posts of user {user_id}, status {:?}, limit {}", filter.status, filter.limit)
}

// Router::new().route("/users/{user_id}/posts", get(user_posts))
// GET /users/42/posts?status=draft  ->  posts of user 42, status Some("draft"), limit 20

Stand-in: a query-string deserialiser

Axum's Query uses serde, which we cannot run on the site. This model shows the same idea in std-only Rust: split on & and =, percent-decode, then convert to a struct with required and optional fields and a default. The error messages play the role of the 400 response.

Rust Stand-in: parsing ?page=2&q=hello+world into a struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Stand-in: Path plus Query together

This second model builds the typical GET /users/{id}/posts?status=...&limit=... call. It splits the URL into the path (captures) and the query, runs both "extractors", and reports which one failed. The point is that each extractor fails independently and before the handler runs.

Rust Stand-in: Path and Query in one request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Common mistakes

  • Putting identifiers in the query (/post?id=7) when they belong in the path.
  • Forgetting that a non-Option field is required.
  • Trusting limit and offset. Clamp them.
  • Expecting Vec<T> to collect repeated keys with the standard Query.
  • Using Query for large or secret data: URLs end up in logs, browser history and proxies. Send those in a request body.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A handler takes Query<Filters> where Filters has a field page: u32 with no default. What happens on GET /items?

    A non-Option field without a serde default is required, so deserialisation fails and the Query rejection (400) is returned.
  2. 2. Which request does Query<Filters> accept if Filters has only q: Option<String>?

    serde ignores unknown keys by default. deny_unknown_fields would change that.
  3. 3. Which extractor must be the last argument of a handler?

    Body extractors implement FromRequest and consume the request, so only one is allowed and it comes last.
  4. 4. How do you protect the database from ?limit=1000000?

    Query values are user input; parsing as a number does not make a value safe.

Summary

  • Query<T> deserialises the query string; Option<T> fields are optional and plain fields are required.
  • Use #[serde(default)] for defaults and clamp user-supplied limits.
  • Unknown keys are ignored; repeated keys need axum_extra or manual handling.
  • Path and Query read only the request head, so they can be combined in any order; a failure answers 400 before your handler runs.

Next: JSON and Form Bodies