expression
REST: preserve old request behavior with defaults
When adding an input field, define what absence means. A documented default should preserve the behavior experienced by existing clients. In this example old requests imply quantity one; an explicit value is retained. Validate the value separately. Standalone synthetic example. Expected stdout (not executed): pen 1 pen 3 Common mistake: Changing a default in place when existing clients depend on its old meaning.
Formal Syntax & Structure
rust syntaxrust
#[serde(default = "default_quantity")]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() { fn default_quantity() -> u32 { 1 } #[derive(Deserialize)] struct Create { name: String, #[serde(default = "default_quantity")] quantity: u32 } for raw in [r#"{"name":"pen"}"#, r#"{"name":"pen","quantity":3}"#] { let input: Create = serde_json::from_str(raw).unwrap(); println!("{} {}", input.name, input.quantity); }}