rust 33 lines · 7 steps

Parsing query strings in Axum handlers

How Axum's Query extractor deserializes URL parameters into a typed struct with sensible defaults.

Explained by highlit
1use axum::{
2 extract::Query,
3 response::IntoResponse,
4 Json,
5};
6use serde::Deserialize;
7 
8#[derive(Debug, Deserialize)]
9pub struct ArticleFilter {
10 #[serde(default)]
11 tag: Vec<String>,
12 #[serde(default)]
13 author: Option<String>,
14 #[serde(default = "default_limit")]
15 limit: u32,
16}
17 
18fn default_limit() -> u32 {
19 20
20}
21 
22pub async fn list_articles(
23 Query(filter): Query<ArticleFilter>,
24) -> impl IntoResponse {
25 let articles = Article::query()
26 .filter_tags(&filter.tag)
27 .filter_author(filter.author.as_deref())
28 .limit(filter.limit)
29 .fetch_all()
30 .await;
31 
32 Json(articles)
33}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1The Query extractor turns raw URL parameters into a validated, typed struct before your handler runs.
  2. 2serde's default attribute lets each field fall back gracefully when a parameter is absent from the request.
  3. 3Building the response from a typed filter keeps handlers thin and pushes query logic into the query builder.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing query strings in Axum handlers — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code