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 axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
rust
use std::net::Ipv4Addr; use std::str::FromStr; #[derive(Debug, Clone, Copy)]
Parsing and matching IPv4 CIDR ranges in Rust
bitwise-operations
parsing
error-handling
Intermediate
8 steps
java
@RestController @RequestMapping("/api/products") public class ProductSearchController {
Binding collection query params in Spring
rest-api
query-parameters
dependency-injection
Intermediate
6 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.