FastAPI interview question · Most asked
How does FastAPI use Pydantic for request validation?
Summary
Request bodies, query models and settings are declared as Pydantic BaseModel classes. FastAPI parses incoming data into them, validates types and constraints, and returns a 422 response with detailed errors on failure.
Longer Answer
Pydantic v2 (with its Rust core, pydantic-core) coerces compatible input (e.g., '3' → 3 in lax mode), enforces constraints (Field(gt=0, max_length=50)), and supports custom validators (@field_validator, @model_validator). Errors include the location (body.price), message and type, which clients can map to form fields.
Code Example
from pydantic import BaseModel, Field, field_validator, EmailStr
class SignUp(BaseModel):
email: EmailStr
password: str = Field(min_length=12)
age: int = Field(ge=18)
@field_validator("password")
@classmethod
def has_digit(cls, v: str) -> str:
if not any(c.isdigit() for c in v):
raise ValueError("password must contain a digit")
return v
Key Points
- Models declared with type hints and
Field()constraints - Invalid input → automatic 422 response
@field_validator/@model_validatorfor custom rules- Strict mode disables coercion
More most-asked FastAPI questions
- When should an endpoint be `async def` versus plain `def` in FastAPI?
- Walk through what happens to a request in FastAPI, from the ASGI server to the response.
- What is FastAPI and what makes it different from Flask or Django?
- How do `yield` dependencies work and why are they used for database sessions?
- How does FastAPI distinguish path, query and body parameters?
- What does `response_model` (or a return annotation) do in FastAPI?
- How does dependency injection with `Depends` work in FastAPI?
- How do you implement OAuth2 password flow with JWT in FastAPI?