rust
67 lines · 10 steps
Building a safe search query in Axum
An Axum handler deserializes query params with sensible defaults and builds a parameterized SQL search with dynamic filters.
Explained by
highlit
1#[derive(Debug, Deserialize)]
2pub struct SearchParams {
3 #[serde(default)]
4 q: String,
5 #[serde(default = "default_page")]
6 page: u32,
7 #[serde(default = "default_per_page")]
8 per_page: u32,
9 #[serde(default)]
10 sort: SortField,
11 status: Option<ArticleStatus>,
12}
13
14fn default_page() -> u32 { 1 }
15fn default_per_page() -> u32 { 20 }
16
17#[derive(Debug, Default, Deserialize)]
18#[serde(rename_all = "snake_case")]
19pub enum SortField {
20 #[default]
21 Newest,
22 Oldest,
23 Title,
24}
25
26#[derive(Serialize)]
27pub struct PaginatedArticles {
28 items: Vec<Article>,
29 page: u32,
30 per_page: u32,
31 total: i64,
32}
33
34pub async fn search_articles(
35 State(pool): State<PgPool>,
36 TypedHeader(accept_lang): TypedHeader<AcceptLanguage>,
37 Query(params): Query<SearchParams>,
38) -> Result<Json<PaginatedArticles>, ApiError> {
39 let per_page = params.per_page.clamp(1, 100);
40 let offset = params.page.saturating_sub(1) * per_page;
41 let locale = accept_lang.preferred().unwrap_or("en");
42
43 let order = match params.sort {
44 SortField::Newest => "published_at DESC",
45 SortField::Oldest => "published_at ASC",
46 SortField::Title => "title ASC",
47 };
48
49 let mut builder = QueryBuilder::new("SELECT * FROM articles WHERE locale = ");
50 builder.push_bind(locale);
51 if !params.q.is_empty() {
52 builder.push(" AND search_vector @@ plainto_tsquery(");
53 builder.push_bind(¶ms.q);
54 builder.push(")");
55 }
56 if let Some(status) = params.status {
57 builder.push(" AND status = ").push_bind(status);
58 }
59 builder.push(format!(" ORDER BY {order} LIMIT "));
60 builder.push_bind(per_page as i64);
61 builder.push(" OFFSET ").push_bind(offset as i64);
62
63 let items: Vec<Article> = builder.build_query_as().fetch_all(&pool).await?;
64 let total = count_matching(&pool, ¶ms, locale).await?;
65
66 Ok(Json(PaginatedArticles { items, page: params.page, per_page, total }))
67}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1serde defaults let you accept partial query strings while guaranteeing every field has a value.
- 2Clamping and saturating arithmetic turn untrusted pagination input into safe, bounded database offsets.
- 3QueryBuilder with push_bind composes conditional SQL while keeping every user value parameterized against injection.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 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
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 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/building-a-safe-search-query-in-axum-explained-rust-671f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.