Skip to content
tezvyn:

Create a generic Pydantic BaseModel for API response wrappers

Source: pydantic.devHardHow cards are made

Create a generic Pydantic BaseModel for API response wrappers
Summary

Pydantic v2 generics and OpenAPI schema generation.

Key points

subclass BaseModel and Generic[T]; type data as T; use ResponseWrapper[User]; note unparametrized TypeVars validate as Any.

What's really being asked

This question probes whether you understand Pydantic v2 generic model mechanics, not just static typing. The interviewer wants to see if you know that BaseModel must explicitly inherit from Generic[T] to carry type parameters through validation and JSON schema generation. They also care whether you understand the runtime behavior of unparametrized TypeVars and how FastAPI or other frameworks expose these types in OpenAPI docs.

The full answer

Four things in order. First, import Generic and TypeVar from typing, create a TypeVar such as T equals TypeVar with the name T, and define class ResponseWrapper inheriting from BaseModel and Generic[T] with fields like data of type T and success of type bool. Second, show concrete usage by parametrizing the model, for example ResponseWrapper[UserOut], which gives both mypy and Pydantic enough information to validate the nested shape and emit a precise JSON schema. Third, explain that if you leave the wrapper unparametrized, Pydantic treats the TypeVar as Any at validation time and the generated OpenAPI schema may show an incomplete or overly permissive component. Fourth, mention that Pydantic v2 handles generic recursion and parametrized subclasses correctly, so you can subclass ResponseWrapper[T] further if needed.

The mistakes people make

Three red flags stand out. One, using Union or Any instead of a TypeVar, which defeats the purpose of a reusable generic wrapper. Two, forgetting to include Generic[T] in the class bases and assuming BaseModel alone propagates type parameters, which breaks both runtime validation and schema generation. Three, claiming that Python generics are only static and do not affect Pydantic validation, when in fact Pydantic v2 resolves generic parameters at runtime to build validators.

What usually comes next

The interviewer may ask how you would constrain T to Pydantic models only, perhaps with a bound or a custom protocol. They might ask what happens to OpenAPI docs when you return a list of ResponseWrapper[Item] from a FastAPI endpoint. Another follow-up is how to handle generic models with default factory fields or recursive type references inside the wrapper.

A concrete example

Import Generic and TypeVar from typing and BaseModel from pydantic. Define T as TypeVar with the name T. Define class ResponseWrapper with bases BaseModel and Generic[T], containing success as bool, data as T, and error as an optional string defaulting to None. Define class UserOut with bases BaseModel, containing id as int and name as str. Concrete parametrization ResponseWrapper[UserOut] gives full schema generation and runtime validation. Instantiating it with success equals True and data as a UserOut instance with id 1 and name Ada produces a fully typed response object.

Interview question

In Pydantic v2, what is the runtime validation behavior of a generic wrapper field typed as T when the model is used without parametrization?

  • a.The field is validated as Any, accepting arbitrary data and generating an overly permissive schemaCorrect
  • b.The TypeVar is inferred from the first assigned value and fixed for subsequent instances
  • c.Pydantic raises a ValidationError because an unbound TypeVar cannot be validated
  • d.Python's static type checker enforces parametrization before Pydantic ever runs validation
Why?

The card explicitly states that unparametrized TypeVars are treated as Any at validation time, yielding an overly permissive OpenAPI schema. Option C is a tempting distractor because developers often assume missing generic parameters cause runtime errors, but Pydantic v2 gracefully falls back to Any instead.

Just read this? Test yourself on what you have been reading.

Read the original → pydantic.dev

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on pydantic — each one lists the topics its interview covers.

See open roles