On this page

Response Models and Output Validation in FastAPI

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

A response model is a Pydantic class that describes the shape of the data an API sends back, separately from whatever internal object the endpoint's function actually works with. This distinction matters because the object a function has access to internally — a database row, an ORM instance, a full user record — often carries fields that shouldn't leave the API at all: a password hash, an internal database ID, a note meant only for other backend systems. response_model is what enforces that boundary: it validates and filters whatever a path operation returns against a separate schema before that data is ever serialized into the response sent to a client.


What a Response Model Does​

Declaring response_model=SomeModel on a route tells FastAPI to take whatever the function returns, validate it against SomeModel's fields, and serialize only what SomeModel declares — anything present on the returned object but absent from the response model simply doesn't make it into the response. This happens regardless of whether the function returns a plain dictionary or an instance of a different Pydantic model entirely, since FastAPI performs this filtering as a separate step after the function runs, not by inspecting what the function happened to return.


Filtering Internal Fields from a Response​


from fastapi import FastAPI

from pydantic import BaseModel



app = FastAPI()



# Internal model (e.g. from a database)

class Task(BaseModel):

    id: int

    title: str

    completed: bool

    internal_notes: str



# Public response model

class TaskResponse(BaseModel):

    title: str

    completed: bool



@app.get("/task", response_model=TaskResponse)

def get_task():

    task = Task(id=1, title="Buy milk", completed=False, internal_notes="Urgent task")

    return task

Task represents the full internal record, including fields — id, internal_notes — that make sense to keep around internally but shouldn't be exposed to a client. get_task builds and returns a full Task instance, but because the route declares response_model=TaskResponse, FastAPI validates that returned object against TaskResponse's two fields and serializes only those, dropping id and internal_notes entirely. Visiting /task returns:


{

  "title": "Buy milk",

  "completed": false

}

and visiting /docs shows the endpoint's documented response schema as TaskResponse, not Task — the documentation reflects exactly what a client will actually receive, not what the function internally constructed.


Filtering Sensitive Data​

The same mechanism applies directly to hiding sensitive fields, not just internal bookkeeping ones:


class User(BaseModel):

    id: int

    username: str

    email: str

    password: str  # sensitive



class PublicUser(BaseModel):

    username: str

    email: str



@app.get("/user", response_model=PublicUser)

def get_user():

    user = User(id=1, username="enrico", email="[email protected]", password="supersecret")

    return user

/user returns only username and email; id and password never reach the serialized response, even though the User instance constructed inside get_user holds both. This is a meaningful safeguard specifically because it applies at the framework level, after the function has already run — a route can't accidentally leak a field it forgot to strip manually, since the filtering happens based on the declared response model rather than on remembering to build a "safe" dictionary by hand inside every endpoint.


Configuring a Response Model for ORM Objects​

Reading data directly from an ORM object — a SQLAlchemy model instance, for example — rather than a plain dictionary requires telling Pydantic to read attributes off the object instead of expecting dictionary keys. The option controlling this is named from_attributes:


from pydantic import BaseModel, ConfigDict



class TaskResponse(BaseModel):

    model_config = ConfigDict(from_attributes=True)



    title: str

    completed: bool

model_config = ConfigDict(from_attributes=True) is the current way to enable this behavior. Older Pydantic material sometimes shows this same setting written as a nested class Config: orm_mode = True instead — that was the syntax in Pydantic 1.x, and the option was both renamed and moved when Pydantic 2 replaced the nested Config class with the model_config attribute; orm_mode no longer exists under that name. from_attributes=True becomes necessary the moment a response model needs to validate data coming from an object with attributes — like a SQLAlchemy row — rather than from a dictionary or another Pydantic model.


Practice: Building a Filtered User Endpoint​


class User(BaseModel):

    id: int

    username: str

    email: str

    password: str

    is_admin: bool



class PublicUser(BaseModel):

    username: str

    email: str



@app.get("/users/me", response_model=PublicUser)

def get_current_user():

    user = User(

        id=7,

        username="enrico",

        email="[email protected]",

        password="supersecret",

        is_admin=True,

    )

    return user

User carries all five fields a full internal record needs, including two — password and is_admin — that have no reason to reach a client response. PublicUser declares only the two fields safe to expose. Because get_current_user declares response_model=PublicUser, the full User instance built inside the function is filtered down before serialization: /users/me returns only {"username": "enrico", "email": "[email protected]"}, and /docs documents PublicUser as the endpoint's response schema — password and is_admin never appear anywhere a client-facing consumer of the API would see them, either in the actual response or in the generated documentation describing it.

Key Takeaways​

response_model separates what a path operation function internally works with from what actually gets sent back to a client, validating and filtering the return value against a distinct schema after the function runs rather than trusting the function to shape its own output correctly. This makes it a genuine safeguard for sensitive or internal-only fields — a password or a database ID left off the response model simply never reaches the serialized response — and it keeps the generated documentation in /docs accurate to what a client will actually receive. Reading response data from ORM objects rather than dictionaries requires model_config = ConfigDict(from_attributes=True) on the response model; this replaced the older, now-renamed orm_mode setting from Pydantic's nested Config class syntax.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Request Models

Next

Error Handling