Python / FastAPI 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 |
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
