expression

REST: parse pagination query defaults

Use a typed query object to parse optional list controls. A missing limit can have a documented default; malformed values are rejected by the extractor. A numeric value still needs a separate range check. The example uses query parsing without a server. Standalone synthetic example. Expected stdout (not executed): 20 0 5 10 Common mistake: Allowing a default to replace malformed input instead of reporting the error.

Formal Syntax & Structure

rust syntaxrust
Query<ListParams>

Working Example

Example Snippetrust
use axum::{Router, Json, body::{Body, to_bytes}, http::{Request, StatusCode}};use serde::{Deserialize, Serialize};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    use axum::{extract::Query, http::Uri};    fn default_limit() -> usize { 20 }    #[derive(Deserialize)]    struct ListParams { #[serde(default = "default_limit")] limit: usize, #[serde(default)] offset: usize }    for raw in ["/items", "/items?limit=5&offset=10"] {        let uri: Uri = raw.parse().unwrap();        let Query(q) = Query::<ListParams>::try_from_uri(&uri).unwrap();        println!("{} {}", q.limit, q.offset);    }}
Rust Reference