expression

Axum: validate a decoded JSON value

Deserialization checks whether input can become a Rust value. Domain validation checks whether the value is acceptable for the application. Here a u16 quantity of zero is structurally valid but violates the allowed range. In-memory standalone Cargo example. Expected stdout (not executed): 422 201 422 Common mistake: Assuming a successful parse proves business validity. The 201 is a simulated result, not a persisted record.

Formal Syntax & Structure

rust syntaxrust
if !(1..=100).contains(&input.quantity) { ... }

Working Example

Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    use axum::{Json, routing::post};    #[derive(serde::Deserialize)] struct Input { quantity: u16 }    async fn create(Json(x): Json<Input>) -> StatusCode {        if (1..=100).contains(&x.quantity) { StatusCode::CREATED } else { StatusCode::UNPROCESSABLE_ENTITY }    }    let app = Router::new().route("/items", post(create));    for body in [r#"{"quantity":0}"#, r#"{"quantity":100}"#, r#"{"quantity":101}"#] {        let r = app.clone().oneshot(Request::builder().method("POST").uri("/items").header("content-type", "application/json").body(Body::from(body)).unwrap()).await.unwrap();        println!("{}", r.status().as_u16());    }}
Rust Reference