expression

REST: separate input DTOs from domain models

A data transfer object (DTO) defines the input accepted from clients. Construct a domain object explicitly after parsing and validation. Assign server-controlled fields independently. Strict unknown-field rejection is one policy; it helps expose typos but can reduce compatibility with newer clients. Standalone synthetic example. Expected stdout (not executed): 7 pen false extra rejected: true Common mistake: Deserializing client input directly into fields that control privilege or workflow.

Formal Syntax & Structure

rust syntaxrust
struct CreateItem { name: String }

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() {    #[derive(Deserialize)]    #[serde(deny_unknown_fields)]    struct CreateItem { name: String }    struct Item { id: u32, name: String, approved: bool }    let input: CreateItem = serde_json::from_str(r#"{"name":"pen"}"#).unwrap();    let item = Item { id: 7, name: input.name, approved: false };    println!("{} {} {}", item.id, item.name, item.approved);    println!("extra rejected: {}", serde_json::from_str::<CreateItem>(r#"{"name":"pen","approved":true}"#).is_err());}
Rust Reference