tezvyn:

Pydantic computed fields in response models

AI-drafted, machine-checkedintermediate
WHAT IT TESTS

Deriving output-only fields.

OUTLINE

a @computed_field decorated property is excluded from input and validation but included in serialization and the OpenAPI schema, ideal for values like full_name derived from other fields.

WHAT THIS TESTS Whether you understand Pydantic v2's mechanism for fields that are computed from other data and appear only in output, and how that maps onto FastAPI response models and docs.

A GOOD ANSWER COVERS A computed field is a method or property decorated with @computed_field. Unlike a regular field, it is not part of the model's input: clients do not send it, and it is not validated as incoming data. Pydantic derives it from existing fields when the model is serialized, and it is included in model_dump, model_dump_json, and the generated JSON schema, so it shows up in FastAPI's OpenAPI docs and in responses. You typically pair @computed_field with @property. This is the clean way to expose derived values such as a full name, an age from a birthdate, a total from line items, or a URL built from an id, without storing redundant data or requiring callers to send it. Because it is recomputed on serialization, it always reflects the current field values.

COMMON WRONG ANSWERS Expecting the computed field to appear among the input fields or be supplied by the client. Confusing it with a Field default value. Using a plain property without @computed_field, which then would not appear in serialized output or the schema. Storing the derived value as a real field that can drift out of sync.

LIKELY FOLLOW-UPS How does it appear in the OpenAPI schema versus a normal field? How does this differ from a model_validator that sets a value? Can a computed field be typed and documented?

ONE CONCRETE EXAMPLE class UserOut(BaseModel): first_name: str; last_name: str; then @computed_field @property def full_name(self) -> str: return f'{self.first_name} {self.last_name}'. A client posts only first_name and last_name; the response includes full_name automatically, for example {'first_name': 'Ada', 'last_name': 'Lovelace', 'full_name': 'Ada Lovelace'}, and the docs list full_name as an output field.

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.