Skillversitas

Response Model

The response_model option tells FastAPI to validate and filter the value your endpoint returns. You define a Pydantic model for the output shape, and FastAPI keeps only the declared fields, converts values, and exposes the model in the OpenAPI docs. It is the API's output contract.

Basic Usage

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

class ItemOut(BaseModel):
    id: int
    name: str
    price: float

@app.get("/items/{item_id}", response_model=ItemOut)
def read_item(item_id: int):
    # internal record may carry extra fields
    return {"id": item_id, "name": "Widget", "price": 9.99, "internal": "secret"}

The response contains only id, name, and price - internal is stripped, and the docs show ItemOut as the response schema.

Why It Matters

  • Security: internal fields (passwords, costs, flags) never leak to clients.
  • Consistency: every endpoint returning an item has the same documented shape.
  • Typing: clients and generated SDKs get a real schema to rely on.
  • Conversion: values are coerced to the declared types on output.

From ORM Objects with from_attributes

When your internal objects are not Pydantic models (SQLAlchemy models, dataclasses), mark the response model to read attributes from them:

class UserOut(BaseModel):
    id: int
    name: str
    model_config = {"from_attributes": True}

@app.get("/users/{user_id}", response_model=UserOut)
def read_user(user_id: int):
    return db.get_user(user_id)  # a SQLAlchemy object works fine

response_model + status

Combine with status_code for the complete contract:

@app.post("/items/", response_model=ItemOut, status_code=201)
def create_item(item: Item):
    return stored_item

Summary

Declare response_model to make your output explicit: FastAPI filters returned data to the model's fields, converts types, and documents the schema. Use from_attributes to serialize ORM objects directly, and pair it with status_code for a complete, testable API contract.