tezvyn:

FastAPI Response Models: Shape Your API's Output

AI-drafted, machine-checkedSource: fastapi.tiangolo.comintermediate
FastAPI Response Models: Shape Your API's Output

A FastAPI `response_model` defines your API's output shape, acting as a data filter and automatic documentation generator. Use it to prevent data leaks and provide clear schemas.

WHY IT EXISTS APIs need to return data in a predictable, documented format. Without a mechanism to enforce this, you might accidentally leak internal data (like a password hash) or return inconsistent structures, breaking client applications. Response models solve this by enforcing a contract for your API's output.

THE MENTAL MODEL Think of a response_model as a stencil for your API's response. You might have a rich internal object with many fields, but you place the stencil over it before sending it to the client. Only the data that fits through the stencil's cutouts—the fields defined in the model—makes it into the final JSON response.

HOW IT WORKS You declare a Pydantic model and pass it to the response_model argument in your path operation decorator (e.g., @app.get("/users/me", response_model=UserOut)). FastAPI uses this model to: first, filter out any fields from your return object that are not in the model; second, convert the data to the correct types; and third, generate an accurate response schema in your OpenAPI documentation. Using a standard Python return type annotation (-> UserOut) achieves the same result.

WHEN TO USE IT Always use a response_model for endpoints that return structured data. It's crucial for creating robust, self-documenting APIs. It's especially useful when your internal data representation (e.g., a database model) contains more fields than you want to expose publicly. This allows you to have separate models for input, database storage, and public output.

WHEN NOT TO USE IT You might skip it for endpoints that return a direct Response object, like a FileResponse or StreamingResponse, where you are manually controlling the entire response body. If you need to dynamically change which output fields are included, use the response_model_include or response_model_exclude parameters instead of omitting the model entirely.

ONE CANONICAL EXAMPLE Imagine a user object from your database contains username, email, and hashed_password. To avoid sending the password, you define a Pydantic model class UserOut(BaseModel): username: str; email: str. By setting response_model=UserOut on your endpoint, even if you return the full user object from your logic, FastAPI automatically filters out the hashed_password field before sending the response.

Read the original → fastapi.tiangolo.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.