FastAPI interview question · Most asked
What does `response_model` (or a return annotation) do in FastAPI?
Summary
It declares the output schema: FastAPI validates and filters the returned data through that model, so extra fields (like password hashes) are excluded, and it documents the response in OpenAPI.
Longer Answer
You can use a return type annotation (-> UserOut) or response_model=UserOut (needed when the function returns something else, like an ORM object or dict). Options like response_model_exclude_unset=True omit fields not explicitly set. Separate input and output models (UserCreate with a password, UserOut without) to avoid leaking data.
Code Example
class UserCreate(BaseModel):
email: EmailStr
password: str
class UserOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
email: EmailStr
@app.post("/users", response_model=UserOut, status_code=201)
async def create_user(data: UserCreate, db: DbSession):
user = await users.create(db, data) # ORM object with hashed_password
return user # hashed_password is filtered out
Key Points
- Filters output to the declared schema
- Documents responses in OpenAPI
- Separate In/Out models
- Return ORM objects with
from_attributes=True
Explanation
Common mistakes
- Returning ORM objects without a response model and leaking internal fields
More most-asked FastAPI questions
- When should an endpoint be `async def` versus plain `def` in FastAPI?
- Walk through what happens to a request in FastAPI, from the ASGI server to the response.
- What is FastAPI and what makes it different from Flask or Django?
- How do `yield` dependencies work and why are they used for database sessions?
- How does FastAPI distinguish path, query and body parameters?
- How does FastAPI use Pydantic for request validation?
- How does dependency injection with `Depends` work in FastAPI?
- How do you implement OAuth2 password flow with JWT in FastAPI?