Appearance
Pydantic Models
9. What is Pydantic, and how does model validation work?
The short answer
Pydantic turns type hints into runtime validation. A class extending BaseModel declares fields with types; when you create it from data, such as JSON or a dict, Pydantic checks and converts each field, for example turning the string "9" into the integer 9, and raises a ValidationError listing every problem. Version 2 has a core written in Rust, pydantic-core, which makes it fast. FastAPI uses Pydantic models for request bodies, responses and settings.
python
from pydantic import BaseModel, Field, ValidationError
class Order(BaseModel):
order_id: int
total_pence: int = Field(ge=0)
note: str | None = None
print(Order.model_validate({"order_id": "9", "total_pence": "100"}).order_id) # 9, converted (1)
try:
Order(order_id="abc", total_pence=-1)
except ValidationError as e:
print(e.error_count()) # 2: both problems reported at once (2)- Lax mode by default: a numeric string becomes an
int. Strict mode turns that off (question 12). - All errors at once, each with a location and message, which FastAPI turns into a
422.
| Method | Does |
|---|---|
Model(**data) or Model.model_validate(data) | Validate a dict or object |
Model.model_validate_json(text) | Parse and validate JSON in one fast step |
obj.model_dump() | To a dict |
obj.model_dump_json() | To a JSON string |
Model.model_json_schema() | JSON Schema, used for OpenAPI |
10. How do Field constraints and validators work?
The short answer
Field(...) adds constraints and metadata to a field: min_length, max_length, gt, ge, lt, le, pattern, default_factory, alias, description and examples. For rules a constraint cannot express, write a @field_validator, which checks or transforms one field, such as normalising an email, or a @model_validator(mode="after"), which runs on the whole model after fields are validated, for rules that involve several fields, such as "passwords must match" or "end date after start date". Raise ValueError with a clear message to fail.
python
from pydantic import BaseModel, Field, field_validator, model_validator
class Signup(BaseModel):
email: str
password: str = Field(min_length=12) # (1)
password_confirm: str
@field_validator("email") # (2)
@classmethod
def normalise_email(cls, v: str) -> str:
v = v.strip().lower()
if "@" not in v:
raise ValueError("not an email address")
return v
@model_validator(mode="after") # (3)
def passwords_match(self) -> "Signup":
if self.password != self.password_confirm:
raise ValueError("passwords do not match")
return self
Signup(email=" Asha@Shop.Example ", password="longenough123", password_confirm="longenough123").email
# 'asha@shop.example'
Signup(email="asha@shop.example", password="longenough123", password_confirm="x")
# ValidationError: Value error, passwords do not match- A declarative constraint: no code needed.
- A field validator can also transform the value; the returned value is stored.
- A model validator sees every field, so cross-field rules go here.
For real email checks, use Pydantic's EmailStr type, which needs the email-validator package.
11. How do serialisation, aliases and computed fields work?
The short answer
model_dump() returns a dict and model_dump_json() a JSON string, with options such as exclude_none, exclude_unset, include and exclude. Aliases let the JSON use different names from your Python attributes, typically camelCase outside and snake_case inside: Field(alias="orderId"), plus populate_by_name=True so either name works on input, and by_alias=True when dumping. @computed_field adds a derived value, such as a formatted total, to the output and the schema.
python
from pydantic import BaseModel, ConfigDict, Field, computed_field
class Order(BaseModel):
model_config = ConfigDict(populate_by_name=True) # (1)
order_id: int = Field(alias="orderId")
total_pence: int = Field(alias="totalPence")
note: str | None = None
@computed_field
@property
def total(self) -> str: # (2)
return f"£{self.total_pence / 100:.2f}"
o = Order.model_validate({"orderId": 7, "totalPence": 4550})
o.model_dump()
# {'order_id': 7, 'total_pence': 4550, 'note': None, 'total': '£45.50'}
o.model_dump(by_alias=True, exclude_none=True) # (3)
# {'orderId': 7, 'totalPence': 4550, 'total': '£45.50'}- Accept both
orderIdfrom JSON andorder_idfrom Python code. - Computed on output, included in the dump and in the OpenAPI schema.
- Camel-case keys for the API, and no
nullfields.
Whole-model camelCase: ConfigDict(alias_generator=to_camel, populate_by_name=True), with to_camel from pydantic.alias_generators, renames every field without writing each alias.
12. Why use separate input, update and output models, and what is strict mode?
The short answer
One model rarely fits every direction. A create model, UserCreate, includes the password and excludes server-set fields like id. An update model, UserUpdate, makes every field optional, and you apply only the fields the client actually sent with model_dump(exclude_unset=True). An output model, UserPublic, contains only what may be shown, never the password hash. This prevents mass assignment, where a client sets is_admin because the model happened to accept it. Strict mode stops type conversion, so "3" is rejected for an int, which is useful for internal contracts.
python
class UserCreate(BaseModel):
email: str
password: str = Field(min_length=12)
class UserUpdate(BaseModel):
name: str | None = None
email: str | None = None
class UserPublic(BaseModel):
id: int
email: str
name: str | None
@app.patch("/users/me")
async def update_me(changes: UserUpdate, user: CurrentUser) -> UserPublic:
patch = changes.model_dump(exclude_unset=True) # (1)
return await users.update(user.id, patch)
UserUpdate(name="Asha").model_dump(exclude_unset=True) # {'name': 'Asha'}
class InternalEvent(BaseModel):
model_config = ConfigDict(strict=True) # (2)
qty: int
InternalEvent(qty="3") # ValidationError: int_type- Only the fields the client sent, so a missing
emailmeans "do not change", not "set to None". - Strict: no automatic conversion from strings.
13. What changed between Pydantic v1 and v2?
The short answer
Pydantic v2, released in 2023, rewrote the core in Rust, making validation roughly 5 to 50 times faster. The API was renamed: parse_obj became model_validate, dict() became model_dump(), json() became model_dump_json(), @validator became @field_validator, @root_validator became @model_validator, and the inner class Config became model_config = ConfigDict(...). Current FastAPI requires Pydantic 2.9 or newer; v1 is no longer supported, so legacy code must be migrated, with the bump-pydantic tool doing much of it.
| Pydantic v1 | Pydantic v2 |
|---|---|
Model.parse_obj(d) | Model.model_validate(d) |
Model.parse_raw(s) | Model.model_validate_json(s) |
obj.dict(), obj.json() | obj.model_dump(), obj.model_dump_json() |
@validator("x") | @field_validator("x") with @classmethod |
@root_validator | @model_validator(mode="before" or "after") |
class Config: orm_mode = True | model_config = ConfigDict(from_attributes=True) |
Optional[int] meant "not required" | int | None is required unless given a default |
The last row catches people: in v2, note: str | None with no default is required, it just may be None. Write note: str | None = None to make it optional.
14. How do you manage configuration with pydantic-settings?
The short answer
pydantic-settings gives you a BaseSettings class whose fields are filled from environment variables, and optionally a .env file, then validated like any model. A missing required setting or a wrong type fails at startup with a clear error. Use env_prefix to namespace variables, SecretStr for secrets so they print as asterisks, nested models for groups of settings, and create one settings object, cached, that endpoints receive through a dependency.
python
from functools import lru_cache
from typing import Annotated
from fastapi import Depends
from pydantic import SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_prefix="SHOP_", env_file=".env") # (1)
database_url: str # (2)
jwt_secret: SecretStr # (3)
debug: bool = False
@lru_cache # (4)
def get_settings() -> Settings:
return Settings()
SettingsDep = Annotated[Settings, Depends(get_settings)]
# with SHOP_DATABASE_URL and SHOP_JWT_SECRET set:
s = get_settings()
print(s.jwt_secret) # **********
print(s.jwt_secret.get_secret_value()) # the real value, only when you ask for it- Reads
SHOP_DATABASE_URL,SHOP_JWT_SECRETand so on, from the environment or.env. - Required: the app fails to start if it is missing.
SecretStrhides the value in logs and tracebacks.- Built once and reused. The same principles as for Node apps apply (environment config).
15. What is TypeAdapter, and how do you validate data that is not a model?
The short answer
TypeAdapter validates and serialises any type, not just BaseModel subclasses: a list[int], a dict[str, Order], a TypedDict, a union, or an Annotated type with constraints. FastAPI creates one automatically when an endpoint parameter or return type is such a type, so you do not need wrapper models or RootModel. Create a TypeAdapter once at module level, because building one is relatively costly, and reuse it.
python
from typing import Annotated
from fastapi import Body
from pydantic import Field, TypeAdapter
PositiveInts = TypeAdapter(list[Annotated[int, Field(gt=0)]]) # (1)
PositiveInts.validate_python(["1", 2]) # [1, 2]
PositiveInts.validate_python([0]) # ValidationError: Input should be greater than 0
@app.post("/cart/items")
async def add_items(sku_ids: Annotated[list[int], Field(min_length=1), Body()]): # (2)
return {"added": len(sku_ids)}- A reusable validator for a plain list type.
- In FastAPI, just annotate the parameter: a non-empty list of integers from the body, no wrapper model needed.