Python / FastAPI Basics Interview Questions
How do you use Pydantic models for data validation and what validation features does FastAPI support?
Pydantic is FastAPI's validation engine. Models are Python classes inheriting from BaseModel where each field is a type-annotated attribute. Pydantic validates on instantiation, raising ValidationError for invalid data. FastAPI catches this and returns a 422 automatically.
from pydantic import BaseModel, Field, field_validator, model_validator from typing import Annotated from datetime import datetime class UserCreate(BaseModel): username: Annotated[str, Field(min_length=3, max_length=50)] email: Annotated[str, Field(pattern=r"^[\w.-]+@[\w.-]+\.\w+$")] age: Annotated[int, Field(ge=18, le=120)] # >= 18 and <= 120 password: str created_at: datetime = Field(default_factory=datetime.utcnow) # Field-level validator @field_validator("username") @classmethod def username_alphanumeric(cls, v: str) -> str: if not v.isalnum(): raise ValueError("Username must be alphanumeric") return v.lower() # Cross-field validator (model level) @model_validator(mode="after") def passwords_match(self) -> "UserCreate": # example: confirm_password field check would go here return self class UserRead(BaseModel): # separate model for responses (no password) username: str email: str age: int created_at: datetime model_config = {"from_attributes": True} # allows ORM object input
Common Field constraints: min_length, max_length, pattern, ge (≥), gt (>), le (≤), lt (<), multiple_of, min_items, max_items.
Best practice: use separate Pydantic models for input (UserCreate) and output (UserRead) to avoid accidentally exposing sensitive fields like passwords in responses.
More Related questions...