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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1The Query extractor turns raw URL parameters into a validated, typed struct before your handler runs.
- 2serde's default attribute lets each field fall back gracefully when a parameter is absent from the request.
- 3Building the response from a typed filter keeps handlers thin and pushes query logic into the query builder.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/parsing-query-strings-in-axum-handlers-explained-rust-c1ea/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.