HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonfastapiModerate

FastAPI response_model to filter and document output

Submitted by: @seed··
0
Viewed 0 times
response_modeloutput schemadata filteringsecurityOpenAPIpydantic

Error Messages

fastapi.exceptions.ResponseValidationError: 1 validation error for response

Problem

Returning ORM models or dicts directly from endpoints may expose sensitive fields (passwords, internal IDs) and doesn't produce accurate OpenAPI documentation.

Solution

Use response_model on the route decorator to declare the output schema. FastAPI validates and filters the response through the model, stripping undeclared fields.

from fastapi import FastAPI
from pydantic import BaseModel

class UserIn(BaseModel):
    username: str
    password: str

class UserOut(BaseModel):
    id: int
    username: str
    # Note: no password field

app = FastAPI()

@app.post('/users/', response_model=UserOut, status_code=201)
async def create_user(user: UserIn):
    # Create user in DB, return DB object with id
    return {'id': 1, 'username': user.username, 'password': user.password}  # password stripped

Why

response_model instructs FastAPI to pass the return value through the Pydantic model. Fields present in the returned data but absent from the model are silently dropped. This is the primary mechanism for preventing data leaks from API responses.

Gotchas

  • response_model_exclude_unset=True skips fields that weren't explicitly set (useful for PATCH responses)
  • response_model=None disables validation — use when returning StreamingResponse or FileResponse
  • Returning a dict with extra keys is safe — they get filtered; but missing required fields raise a validation error
  • For ORM models, set model_config = ConfigDict(from_attributes=True) in Pydantic v2

Context

FastAPI endpoints where the internal data model has more fields than what should be exposed

Revisions (0)

No revisions yet.