Pydantic Interview Questions with Answers
Basic Questions
Q: What is Pydantic?
A: Pydantic is a Python library used for data validation and settings management using Python type
annotations.
Q: What is BaseModel in Pydantic?
A: BaseModel is the core class you inherit from to create data models in Pydantic.
Q: How does Pydantic handle type coercion?
A: Pydantic will automatically convert input types where possible (e.g., converting '123' to integer
123).
Q: What is a ValidationError in Pydantic?
A: An error raised when the input data does not conform to the defined types or constraints.
Q: Is Pydantic mutable or immutable by default?
A: Pydantic models are mutable by default, but can be made immutable using 'Config' class.
Intermediate Questions
Q: How do you provide default values in Pydantic models?
A: By assigning them in the class definition, or using Field(default=...).
Q: How do you validate custom logic in Pydantic?
A: By using the @validator decorator.
Q: How can you nest Pydantic models?
A: By using another Pydantic model as a type for a field.
Q: Difference between Field() and normal assignment?
A: Field() allows setting metadata like title, description, and validation constraints.
Q: What’s the purpose of the Config class in Pydantic?
A: To customize model behavior, such as enabling ORM mode, making the model immutable, etc.
Advanced / Real-World Questions
Q: How does Pydantic work with FastAPI?
A: FastAPI uses Pydantic for data validation of request and response bodies.
Q: Can you exclude fields when exporting a model to JSON?
A: Yes, using the 'exclude' argument in .dict() or .json().
Q: What’s the difference between .dict() and .json()?
A: .dict() returns a Python dict, while .json() returns a JSON string.
Q: How to create read-only models in Pydantic?
A: By setting 'frozen = True' in the Config class.
Q: How to handle optional fields?
A: By using Optional from the typing module (e.g., Optional[str]).