What is Pydantic and how does it work in FastAPI?
Answer
Pydantic is a Python data validation library that uses type annotations to validate and serialize data. In FastAPI, Pydantic models define request and response schemas. Define a model: from pydantic import BaseModel; class User(BaseModel): name: str; age: int; email: str. Use as request body: @app.post('/users') async def create(user: User): .... FastAPI automatically validates the request JSON against the User model, returning a 422 Unprocessable Entity with detailed errors if validation fails. Pydantic supports: default values, optional fields (Optional[str]), validators (@validator), custom types, and nested models. It also handles serialization: converting ORM objects to JSON-serializable dicts via orm_mode = True (Pydantic v1) or from_attributes = True (Pydantic v2).