expression

REST: separate parsing from business validation

A syntactically valid JSON body can violate application rules. First deserialize the request, then check domain constraints before modifying storage. Here quantity zero is rejected by an explicit policy using 422; the allowed range is illustrative, not a framework default. Standalone synthetic example. Expected stdout (not executed): 422 204 Common mistake: Equating successful JSON parsing with permission to execute a business operation.

Formal Syntax & Structure

rust syntaxrust
Json<T> → validate(T) → domain operation

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::routing::post;    #[derive(Deserialize)]    struct Input { quantity: u32 }    async fn create(Json(input): Json<Input>) -> StatusCode {        if (1..=100).contains(&input.quantity) { StatusCode::NO_CONTENT }        else { StatusCode::UNPROCESSABLE_ENTITY }    }    let app = Router::new().route("/validate", post(create));    for body in [r#"{"quantity":0}"#, r#"{"quantity":2}"#] {        let req = Request::builder().method("POST").uri("/validate").header("content-type", "application/json").body(Body::from(body)).unwrap();        println!("{}", app.clone().oneshot(req).await.unwrap().status().as_u16());    }}
Rust Reference