Python / FastAPI Interview Questions
What are the key differences between Pydantic v1 and v2, and how does FastAPI use Pydantic v2?
FastAPI 0.100+ fully supports Pydantic v2, which is a complete rewrite in Rust offering 5–50× speed improvements. Several APIs changed between v1 and v2.
| v1 (old) | v2 (current) | Notes |
|---|---|---|
| .dict() | .model_dump() | Serialise model to dict |
| .json() | .model_dump_json() | Serialise to JSON string |
| .parse_obj() | .model_validate() | Create model from dict |
| .schema() | .model_json_schema() | Get JSON schema |
| @validator | @field_validator | Field-level validation |
| @root_validator | @model_validator | Model-level validation |
| class Config: | model_config = ConfigDict() | Model configuration |
| orm_mode=True | from_attributes=True | Enable ORM object input |
from pydantic import BaseModel, field_validator, model_validator, ConfigDict
from typing import Self
class OrderItem(BaseModel):
product_id: int
quantity: int
unit_price: float
@field_validator("quantity")
@classmethod
def quantity_positive(cls, v: int) -> int:
if v <= 0:
raise ValueError("quantity must be positive")
return v
class Order(BaseModel):
items: list[OrderItem]
discount: float = 0.0
model_config = ConfigDict(from_attributes=True) # replaces orm_mode
@model_validator(mode="after")
def discount_valid(self) -> Self:
if self.discount < 0 or self.discount > 1:
raise ValueError("discount must be between 0 and 1")
return self
@property
def total(self) -> float:
subtotal = sum(i.quantity * i.unit_price for i in self.items)
return round(subtotal * (1 - self.discount), 2)
# Serialisation
order = Order(items=[OrderItem(product_id=1, quantity=2, unit_price=9.99)])
print(order.model_dump()) # dict
print(order.model_dump_json()) # JSON bytes
print(order.model_json_schema()) # JSON Schema
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...
