Create a generic Pydantic BaseModel for API response wrappers

WHAT IT TESTS: Pydantic v2 generics and OpenAPI schema generation. ANSWER OUTLINE: subclass BaseModel and Generic[T]; type data as T; use ResponseWrapper[User]; note unparametrized TypeVars validate as Any.
WHAT IT TESTS: Pydantic v2 generic models, TypeVar semantics, and OpenAPI schema generation. ANSWER OUTLINE: first, subclass BaseModel and Generic[T]; second, type a field as T; third, show concrete parametrization like ResponseWrapper[User] for full static and runtime checks; fourth, note unparametrized TypeVars fall back to Any and produce vague schemas. RED FLAG: using Union instead of Generic, omitting Generic from bases, or claiming BaseModel alone handles type params without inheritance.
Read the original → pydantic.dev
- #pydantic
- #python-generics
- #fastapi
- #openapi
- #typevar
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.