expression

REST: project public response fields

The response DTO is a deliberate public representation rather than a dump of internal data. Map only fields the client needs. This example excludes an internal cost field without requiring it to be serializable. Standalone synthetic example. Expected stdout (not executed): 7 pen internal field exposed: false Common mistake: Assuming every field in a database record belongs in a public response.

Formal Syntax & Structure

rust syntaxrust
impl From<&Item> for ItemView

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() {    struct Item { id: u32, name: String, internal_cost: u32 }    #[derive(Serialize)]    struct ItemView { id: u32, name: String }    impl From<&Item> for ItemView {        fn from(item: &Item) -> Self { Self { id: item.id, name: item.name.clone() } }    }    let item = Item { id: 7, name: "pen".into(), internal_cost: 12 };    let data = serde_json::to_value(ItemView::from(&item)).unwrap();    println!("{} {}", data["id"], data["name"].as_str().unwrap());    println!("internal field exposed: {}", data.get("internal_cost").is_some());}
Rust Reference