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"> 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" />

Prev Next

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.

Pydantic v1 vs v2 key changes
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_validatorField-level validation
@root_validator@model_validatorModel-level validation
class Config:model_config = ConfigDict()Model configuration
orm_mode=Truefrom_attributes=TrueEnable 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
What is the Pydantic v2 replacement for the v1 .dict() method?
What replaces orm_mode=True in Pydantic v2?

Invest now in Acorns!!! 🚀 Join Acorns and get your $5 bonus!

Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!

Earn passively and while sleeping

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...

What is FastAPI and what are its key advantages over Flask or Django REST Framework? How do you create and run a minimal FastAPI application? What is the difference between path parameters and query parameters in FastAPI? How do you receive and validate a JSON request body in FastAPI? How do you use Pydantic models for data validation and what validation features does FastAPI support? What is the response_model parameter in FastAPI and why should you use it? How do you add validation constraints to path and query parameters using Path() and Query()? How do you control HTTP status codes and return custom responses in FastAPI? What is FastAPI's dependency injection system and how do you use it? How do you organise a FastAPI application with multiple routers (APIRouter)? What is middleware in FastAPI and how do you add custom middleware? When should you use async def vs def for route handlers in FastAPI? What are BackgroundTasks in FastAPI and when should you use them? How do you implement OAuth2 password flow with JWT tokens in FastAPI? How do you implement role-based access control (RBAC) using FastAPI dependencies? How do you integrate an async SQLAlchemy database with FastAPI? How do you manage database schema migrations in a FastAPI project with Alembic? How do you write tests for a FastAPI application using pytest and TestClient? How do you create custom exception handlers in FastAPI? How do you handle form data and file uploads in FastAPI? How do you manage environment variables and settings in FastAPI with Pydantic Settings? How do you run startup and shutdown logic in FastAPI using lifespan? How do you implement WebSocket endpoints in FastAPI? How do you containerise and deploy a FastAPI application with Docker? What are the key production deployment considerations for a FastAPI application? What are the key differences between Pydantic v1 and v2, and how does FastAPI use Pydantic v2? How do you add caching to FastAPI endpoints to improve performance? How do you customise the OpenAPI documentation in FastAPI? How do you integrate FastAPI with Celery for reliable background task processing? How do you measure and improve the performance of a FastAPI application? How do you use class-based dependencies and sub-dependencies in FastAPI? How do you test async FastAPI endpoints and async dependencies? How do you stream large responses in FastAPI using StreamingResponse? How do you add GraphQL support to a FastAPI application with Strawberry? How does FastAPI handle validation errors and how can you customise the error response format? What is the scope of a FastAPI dependency, and how do you share state across requests? How do you read HTTP headers and cookies in FastAPI? What are the most important FastAPI best practices for a production-ready API?
Show more question and Answers...

Tools

Comments & Discussions