FastAPI: From Basics to Production · Pydantic v2 in Depth

Serialization, Aliases and ORM Mode

Control output with model_dump, aliases, computed fields and from_attributes.

model_dump() and model_dump_json() serialize models, with options like exclude_none and by_alias. Use alias/serialization_alias and alias_generator=to_camel to expose camelCase JSON while keeping snake_case in Python. ConfigDict(from_attributes=True) lets you validate ORM objects directly. @computed_field adds derived values to output.

from pydantic import BaseModel, ConfigDict, computed_field
from pydantic.alias_generators import to_camel


class OrderOut(BaseModel):
    model_config = ConfigDict(from_attributes=True, alias_generator=to_camel, populate_by_name=True)

    id: int
    customer_email: str
    subtotal_cents: int
    tax_cents: int

    @computed_field
    @property
    def total_cents(self) -> int:
        return self.subtotal_cents + self.tax_cents


order = OrderOut.model_validate(orm_order)       # from a SQLAlchemy object
order.model_dump(by_alias=True)
# {'id': 1, 'customerEmail': '...', 'subtotalCents': 1000, 'taxCents': 80, 'totalCents': 1080}

Common pitfalls

  • Forgetting from_attributes=True when validating ORM objects.
  • Lazy-loaded relationships triggering queries (or errors in async) during serialization.
  • Inconsistent casing between endpoints.

Key points

  • from_attributes for ORM objects
  • Aliases for camelCase APIs
  • computed_field for derived output

Further reading: Pydantic: Serialization

Practice questions

Why can serializing SQLAlchemy objects fail in async apps?

Answer

Accessing an unloaded relationship triggers lazy loading, which requires I/O and isn't allowed implicitly with async sessions (MissingGreenlet). Eager-load needed relationships.

How do you return camelCase JSON while using snake_case attributes?

Answer

Use an alias generator (to_camel) in the model config; FastAPI serializes by alias for response models.

Open in the app to mark lessons complete, take notes and track your progress.