FastAPI · API Design
FastAPI Response Models: Keep Internal Fields Out of Your API
Define an explicit output contract to filter internal fields and make API responses predictable.

A database record often contains more information than an API client needs. Returning every field creates an accidental contract and can expose internal data.
Define the public shape
Create a Pydantic output model containing only fields clients should receive. FastAPI uses response_model to validate, serialize and filter ordinary returned data, while documenting the response schema.
For example, define UserPublic with id: int and display_name: str. Declare the route with @app.get("/users/{user_id}", response_model=UserPublic). If the handler returns a dictionary containing id, display_name and password_hash, the output model excludes password_hash from the serialized response.
Keep responsibilities separate
Filtering fields does not establish who may access a record. Apply authentication and authorization before returning it. Avoid returning a Response directly when expecting automatic model filtering, because that bypasses this processing.
Test the boundary
Assert the exact JSON keys in endpoint tests, including the absence of password hashes and private metadata. Missing required output fields represent a server-side bug, so handle them through monitoring and fixes rather than weakening the contract.
Review output models whenever internal records change.