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

← All FastAPI questions