Full answer
Validation turns input into Python objects; serialisation turns objects into output. v2 gives hooks for the second half.
class StudentOut(BaseModel):
first: str
last: str
email: str
born: date
@computed_field
@property
def full_name(self) -> str:
return f"{self.first} {self.last}"
@field_serializer("email")
def mask_email(self, value: str) -> str:
name, _, domain = value.partition("@")
return f"{name[0]}***@{domain}"
@field_serializer("born", when_used="json")
def born_as_text(self, value: date) -> str:
return value.strftime("%d %b %Y")computed_fieldon a@propertyaddsfull_nametomodel_dump(), JSON output and the OpenAPI schema (marked read-only in serialisation mode). The return annotation is used for the schema.field_serializerreceives the value (and optionallyinfo);when_usedcan be"always","json","json-unless-none"or"unless-none". Use it for presentation concerns such as masking, rounding and date formats.model_serializerreplaces the whole dump: return a dict (plain mode) or wrap the default (mode="wrap", receiving ahandler) to add or drop keys conditionally.serialization_aliasandField(exclude=True)remove or rename fields without functions.
In FastAPI, response models separate this from storage: the database model holds raw data, the response model formats it. Cautions: serializers run on every response, so keep them cheap; do not hide security-critical data only with a serializer on a shared model (use a separate response model); and remember response_model_exclude_unset interacts with computed fields (they are always included).
Because FastAPI documents the response model, clients see computed fields in generated types. Serialisers do not affect validation, so round trips (response fed back as request) need matching input models.
from datetime import date
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, computed_field, field_serializer, model_serializer
app = FastAPI()
class StudentOut(BaseModel):
first: str
last: str
email: str
born: date
internal_note: str = ""
@computed_field
@property
def full_name(self) -> str:
return f"{self.first} {self.last}"
@field_serializer("email")
def mask_email(self, value: str) -> str:
name, _, domain = value.partition("@")
return f"{name[0]}***@{domain}"
@field_serializer("born", when_used="json")
def born_as_text(self, value: date) -> str:
return value.strftime("%d %b %Y")
@model_serializer(mode="wrap")
def drop_empty_notes(self, handler):
data = handler(self)
if not data.get("internal_note"):
data.pop("internal_note", None)
return data
@app.get("/student", response_model=StudentOut)
def student():
return {"first": "Asha", "last": "Rao", "email": "asha@example.com", "born": date(2009, 3, 4)}
s = StudentOut(first="Ravi", last="Iyer", email="ravi@example.com", born=date(2008, 1, 9))
print(s.model_dump())
print(s.model_dump(mode="json"))
c = TestClient(app)
print(c.get("/student").json())
schema = c.get("/openapi.json").json()["components"]["schemas"]["StudentOut"]
print(sorted(schema["properties"]), schema["properties"]["full_name"].get("readOnly"))
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'first': 'Ravi', 'last': 'Iyer', 'email': 'r***@example.com', 'born': datetime.date(2008, 1, 9), 'full_name': 'Ravi Iyer'} {'first': 'Ravi', 'last': 'Iyer', 'email': 'r***@example.com', 'born': '09 Jan 2008', 'full_name': 'Ravi Iyer'} {'first': 'Asha', 'last': 'Rao', 'email': 'a***@example.com', 'born': '04 Mar 2009', 'full_name': 'Asha Rao'} ['born', 'email', 'first', 'full_name', 'internal_note', 'last'] True
Key points
- field_serializer formats or masks one field
- computed_field adds derived output and schema
- model_serializer controls the whole dump; wrap mode adds or removes keys
- when_used limits a serializer to JSON mode
- Use separate response models for security-critical hiding
Common mistakes
- Hiding secrets with a serializer on a model that is also used elsewhere
- Expensive work inside serializers that run on every response
- Expecting serializers to change validation of incoming data
- Forgetting that computed fields appear in the schema and clients rely on them
Follow-ups
- How does model_serializer(mode='wrap') differ from plain mode?
- How do you exclude a field only in responses?
- How do computed fields appear in OpenAPI?
Tips
- Name the three tools
- Explain when_used
- Separate storage and response models