Python / FastAPI 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 inputCommon 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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
