FastAPI · Concept
Request validation with Pydantic v2
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
How does FastAPI validate a request body with Pydantic v2? Show me how you'd make sure end_date is after start_date, and reject fields the client shouldn't send.
Then
Follow-ups the interviewer asks next
- The client sends
"age": "25"as a string. Does it pass, and how do you make it fail? - What does the client get back when validation fails?
- How do you return a user without
password_hash? - How do you handle a PATCH where the client sends only two fields?
- What changed from Pydantic v1 that breaks old code?
The answer
What a strong answer covers
- Declare a
BaseModeland use it as the endpoint's parameter; FastAPI reads the JSON body, Pydantic checks and converts the types, and the endpoint gets a typed object. - One-field rules:
Field(gt=0, max_length=...)or@field_validator("pincode"). Rules across fields:@model_validator(mode="after")that raisesValueErrorwhenend_date <= start_date. - Unknown fields:
model_config = ConfigDict(extra="forbid"); the default is to ignore them. - The default lax mode turns
"25"into25;strict=True(per field or per model) rejects it. - Errors: FastAPI answers 422 with a
detaillist giving the location, message and type of each error. - Output: a separate response model (
response_model=UserOut) so internal fields never leave;model_dump(exclude_unset=True)for PATCH so only the fields sent are updated. - v1 to v2 renames:
.dict()→model_dump(),.parse_obj()→model_validate(),@validator→@field_validator,orm_mode→from_attributes=True, the innerConfigclass →model_config. As of Nov 2026 Pydantic is 2.14, and FastAPI no longer accepts v1 models.
The red pen
Common traps
Avoid:validating by hand inside the endpoint; one model for input, output and the database; float for money.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.