tezvyn:

How do you define a Pydantic model for FastAPI request body validation?

AI-drafted, machine-checkedSource: fastapi.tiangolo.combeginner
How do you define a Pydantic model for FastAPI request body validation?
WHAT IT TESTS

Schema validation via Python type hints.

ANSWER OUTLINE

Subclass BaseModel with id int, email str, full_name str|None; pass it as a route param so FastAPI validates JSON and returns 422s.

RED FLAG

Saying manual request.json() parsing.

WHAT THIS TESTS: This question checks whether you treat API boundaries as schema contracts rather than loose dictionaries. Even at senior levels, interviewers want to see that you understand declarative validation, type safety, and framework ergonomics. It also reveals if you know the difference between Pydantic as a modeling layer and FastAPI as the HTTP layer that consumes it, and whether you can articulate the automatic error handling that replaces manual try except blocks.

A GOOD ANSWER COVERS: Four things in order. First, import BaseModel from pydantic. Second, define a class that inherits from BaseModel and annotate id as int, email as str, and full_name as Optional[str] or str | None. Third, declare the model as a parameter in the path operation function, for example async def create_user(user: User):. Fourth, explain that FastAPI inspects the type annotation, expects a JSON body, parses it, validates field types and requiredness, and either injects a populated instance or returns a 422 Unprocessable Entity with detailed error locations.

COMMON WRONG ANSWERS: Three red flags stand out. One, saying you manually call await request.json() and then feed it into the model constructor; this ignores FastAPI's automatic dependency injection and validation pipeline. Two, using standard dataclasses without Pydantic and claiming FastAPI will still validate fields; it will not. Three, forgetting that optional fields need an explicit None default or Optional annotation, which causes the field to be treated as required and leads to unexpected 422 errors.

LIKELY FOLLOW-UPS: The interviewer may ask how you handle nested models, how to add field constraints like email regex or min length, how Pydantic v2 differs from v1 in validation behavior, or how FastAPI generates OpenAPI schemas from these models automatically without extra configuration.

ONE CONCRETE EXAMPLE: from pydantic import BaseModel; class User(BaseModel): id: int; email: str; full_name: str | None = None; from fastapi import FastAPI; app = FastAPI(); @app.post("/users/"); async def create_user(user: User): return user. When a client posts JSON missing the email key, FastAPI responds with a 422 and a JSON error body pointing exactly at the email field without any custom error handling code.

Source: fastapi.tiangolo.com

Read the original → fastapi.tiangolo.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.