rust
57 lines · 8 steps
Paginated, filtered product listing in Axum
An Axum handler parses query params into a typed struct and runs one SQL query where each filter is optional.
Explained by
highlit
1use axum::{
2 extract::{Query, State},
3 http::StatusCode,
4 Json,
5};
6use serde::Deserialize;
7use sqlx::PgPool;
8
9fn default_page() -> u32 {
10 1
11}
12
13fn default_per_page() -> u32 {
14 20
15}
16
17#[derive(Debug, Deserialize)]
18pub struct ListProductsParams {
19 #[serde(default)]
20 pub search: Option<String>,
21 pub category_id: Option<i64>,
22 pub in_stock: Option<bool>,
23 #[serde(default = "default_page")]
24 pub page: u32,
25 #[serde(default = "default_per_page")]
26 pub per_page: u32,
27}
28
29pub async fn list_products(
30 State(pool): State<PgPool>,
31 Query(params): Query<ListProductsParams>,
32) -> Result<Json<Vec<Product>>, StatusCode> {
33 let per_page = params.per_page.clamp(1, 100) as i64;
34 let offset = (params.page.saturating_sub(1) as i64) * per_page;
35
36 let products = sqlx::query_as::<_, Product>(
37 r#"
38 SELECT id, name, price, category_id, stock
39 FROM products
40 WHERE ($1::text IS NULL OR name ILIKE '%' || $1 || '%')
41 AND ($2::bigint IS NULL OR category_id = $2)
42 AND ($3::bool IS NULL OR (stock > 0) = $3)
43 ORDER BY name
44 LIMIT $4 OFFSET $5
45 "#,
46 )
47 .bind(params.search)
48 .bind(params.category_id)
49 .bind(params.in_stock)
50 .bind(per_page)
51 .bind(offset)
52 .fetch_all(&pool)
53 .await
54 .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
55
56 Ok(Json(products))
57}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Serde defaults let optional query params fall back to sensible values without manual checks.
- 2A single SQL statement with NULL guards handles every combination of optional filters cleanly.
- 3Clamping and saturating arithmetic turn untrusted pagination input into safe bounds.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 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
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/paginated-filtered-product-listing-in-axum-explained-rust-56ac/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.