Python / FastAPI Basics Interview Questions
What is the response_model parameter in FastAPI and why should you use it?
The response_model parameter on a route decorator tells FastAPI which Pydantic model to use for filtering and serialising the response. Even if the endpoint returns more data internally, only the fields defined in the response model are included in the JSON output.
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class UserIn(BaseModel): username: str password: str email: str class UserOut(BaseModel): username: str email: str # password intentionally excluded # response_model filters the output â password never appears in response @app.post("/users", response_model=UserOut) def create_user(user: UserIn) -> UserOut: # Even if we return the full user object, password is stripped return user # FastAPI applies UserOut filtering # response_model_exclude_unset: only include fields explicitly set by caller @app.get("/items/{id}", response_model=UserOut, response_model_exclude_unset=True) def get_item(id: int): return {"username": "alice", "email": "a@b.com"} # List response @app.get("/users", response_model=list[UserOut]) def list_users(): return [{"username": "alice", "email": "a@b.com", "password": "secret"}]
| Option | Effect |
|---|---|
| response_model=UserOut | Filters output to only UserOut fields |
| response_model_exclude_unset=True | Omits fields not explicitly set (no default-value noise) |
| response_model_exclude_none=True | Omits fields that are None |
| response_model_include={'field'} | Only include specific fields |
| response_model_exclude={'field'} | Exclude specific fields |
More Related questions...