Pydantic
35 bites tagged Pydantic — interview questions with model answers, and 60-second explainers.
Pydantic computed fields in response models
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. Deriving output-only fields.
Mapping camelCase JSON to snake_case Pydantic fields
Set an alias_generator (to_camel) plus populate_by_name in model config, accept aliases on input, and serialize with by_alias=True so responses come out camelCase. Pydantic field aliasing across the JSON boundary.
Pydantic BaseModel vs dataclasses in FastAPI
BaseModel validates and coerces data at runtime, parses and serializes JSON, integrates with OpenAPI schema generation, and supports rich validators; dataclasses only store data with no validation. Why FastAPI standardizes on Pydantic.
How FastAPI uses type hints for validation
Hints drive parsing, validation, and conversion; a path declared int is coerced or returns 422; OpenAPI is auto-generated. Whether you know FastAPI leans on Pydantic and type hints.
How do you manage configuration and secrets for a containerized FastAPI app?
Tests 12-factor config separation and Docker secret hygiene. A strong answer uses pydantic-settings with runtime env vars, lru_cache, and keeps .env out of the image. Red flag: baking credentials into Dockerfile layers or committing .env files.
How can you provide a Swagger UI example for a Pydantic body?
Tests whether you know FastAPI generates OpenAPI schema from Pydantic metadata. A strong answer names Field(example=...) for per-field samples and Body(example=...) for the full payload.
Explain SQLAlchemy ORM vs Pydantic models in FastAPI
This tests separation of database schema from API contracts. A strong answer distinguishes SQLAlchemy table rows from Pydantic validation and OpenAPI generation, and notes that create schemas exclude auto-generated IDs.
How would you use a Pydantic response_model to enforce output structure?
Tests separation of internal models from API contracts. Define a Pydantic output model with only safe fields, set it as the endpoint response_model, and let FastAPI filter and validate.
How do you define a Pydantic model and use it in FastAPI?
Subclass BaseModel with name str and age int, then type-hint the parameter with the model. Whether you use Pydantic BaseModel for request body validation in FastAPI.
Ensure end_date is after start_date in Pydantic
Tests whether you know field validators see only one value and cannot compare siblings. Use a model validator instead, which receives the full instance and can compare start_date and end_date. Red flag: a field validator referencing the other field.
Model an Order with a nested Product list in Pydantic
It tests Pydantic nested model composition. Define Product as BaseModel, then Order with products: list[Product]; Pydantic recursively coerces each dict and raises ValidationError on failure. A red flag is insisting on manual iteration.
How do you prevent password_hash from appearing in a FastAPI response?
Tests FastAPI response filtering and the security practice of separating DB schemas from API contracts. A strong answer proposes a dedicated output model omitting the field, then cites response_model_exclude. Red flag: manual dict deletion or monkey-patching.
Implement a custom validator for a single Pydantic model field
Use @field_validator as a classmethod, raise ValueError on failure, return the value. Your grasp of Pydantic v2 field validation hooks. Validating outside the model or confusing v1 @validator with v2.
Enforce positive price and SKU format using Pydantic Field without custom validators
Use Field(gt=0) for price and Field(pattern=r'^ITEM-\d{5}$') for SKU; mention Annotated. Pydantic V2 Field constraints vs custom validators. Suggesting @field_validator or conint/constr.
What is the difference between a Pydantic default and Optional field?
Both forms are non-required; str = 'guest' rejects None, Optional[str] = None accepts it. Separation of type constraints from requiredness.
How does Pydantic handle extra JSON fields, and how to configure it?
This tests Pydantic's data filtering behavior and configuration. By default, Pydantic ignores extra fields silently. Set model_config = ConfigDict(extra='forbid' or 'allow') to change it. A red flag is claiming FastAPI 422s by default on unknown fields.
How do you define a Pydantic model for FastAPI request body validation?
Subclass BaseModel with id int, email str, full_name str|None; pass it as a route param so FastAPI validates JSON and returns 422s. Schema validation via Python type hints. Saying manual request.json() parsing.
FastAPI non-integer query param default behavior
Tests FastAPI's automatic Pydantic validation and default error contracts. Strong answer: 422 Unprocessable Entity with JSON detail array containing loc, msg, and type fields. Red flag: saying 400 Bad Request or manual validation is needed.
Create a generic Pydantic BaseModel for API response wrappers
Subclass BaseModel and Generic[T]; type data as T; use ResponseWrapper[User]; note unparametrized TypeVars validate as Any. Pydantic v2 generics and OpenAPI schema generation.
How does FastAPI leverage Pydantic for request validation and serialization?
This tests your understanding of FastAPI's declarative validation. Explain that type hints trigger auto-parsing, Pydantic enforces schemas and errors, and return types auto-serialize responses. Red flag: manually parsing request.body() or json.loads in routes.
Explain Python type hints and their importance in FastAPI
Define hints as declarations; explain FastAPI uses them with Pydantic to validate requests and OpenAPI docs. If you know FastAPI uses type hints for validation and docs. Seeing hints as IDE-only.
Custom Field Serialization with @field_serializer
@field_serializer is an exit-only adapter for one field: it reshapes data leaving the Pydantic model without changing internals. Use it to format decimals, mask secrets, or tweak datetimes for FastAPI JSON. Never use it for validation; it only runs on output.
Per-Field Validation with @field_validator
@field_validator scrubs a single Pydantic field before it enters the model. Use it for rules like 'password must contain a digit' or 'port must exceed 1024'. It only sees one field at a time, so cross-field checks belong in a model validator instead.
Serialize Pydantic Models with model_dump
model_dump turns a Pydantic model into a plain Python dict, bridging typed objects and JSON serializers in FastAPI endpoints. Call it when you need raw data before returning a response. Do not confuse it with model_dump_json, which emits a string, not a dict.
Get Pydantic bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.