Serde request validation
Quick answer
Deserializing JSON checks its representation and Rust field types, but a well-formed value may still violate a business rule. Validate both layers before changing state.
Separate wire shape from domain rules
A request DTO can use #[serde(deny_unknown_fields)] when the contract requires rejecting unexpected fields. Do not apply it blindly to APIs designed for forward compatibility. Limit the body size before deserialization. Then check semantic constraints such as quantity greater than zero and at most 100. In the examples use the existing candidate serde 1.0.228 with derive and serde_json 1.0.140. These functions do not themselves implement an HTTP body limit.
use serde::Deserialize;#[derive(Deserialize)]#[serde(deny_unknown_fields)]struct Create { quantity: u32 }fn main() { let x: Create = serde_json::from_str(r#"{"quantity":3}"#).unwrap(); println!("{}", x.quantity); println!("{}", serde_json::from_str::<Create>(r#"{"quantity":3,"extra":true}"#).is_err());}Manual local Rust/Cargo candidate; not executed. Expected behavior:
3trueThe extra field violates this particular strict contract.
fn validate(q: u32) -> Result<u32, &'static str> { if (1..=100).contains(&q) { Ok(q) } else { Err("quantity outside range") }}fn main() { println!("{:?}", validate(0)); println!("{:?}", validate(3)); }Expected stdout (not executed):
Err("quantity outside range")Ok(3)Zero can deserialize as u32 but is not a valid order quantity.
Common mistake
Do not trust a DTO simply because deserialization succeeded.
Try it yourself
Test a negative JSON number, a missing quantity and the boundary value 100.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Serde request validation — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A forward-compatible API intentionally ignores unknown optional fields. Should deny_unknown_fields be applied automatically?
Serde request validation — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use serde::Deserialize; #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Create { quantity: u32 } fn main() { let x: Create = serde_json::from_str(r#"{"quantity":3}"#).unwrap(); println!("{}", x.quantity); println!("{}", serde_json::from_str::<Create>(r#"{"quantity":3,"extra":true}"#).is_err()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Serde request validation — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn validate(q: u32) -> Result<u32, &'static str> { if (1..=100).contains(&q) { Ok(q) } else { Err("quantity outside range") } } fn main() { println!("{:?}", validate(0)); println!("{:?}", validate(3)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.