Skip to content
FastAPI

Response Model

Shape and filter responses with response_model.

By EZ4Code Team
responsepydantic

Code

from pydantic import BaseModel
from fastapi import FastAPI

app = FastAPI()

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

class UserOut(BaseModel):
    username: str
    id: int

@app.post("/users", response_model=UserOut)
def create_user(user: UserIn):
    stored = {"username": user.username, "password": "hashed", "id": 1}
    return stored

@app.get("/users/{uid}", response_model=list[UserOut])
def list_users(uid: int):
    return [{"username": "alice", "id": 1}, {"username": "bob", "id": 2}]

Explanation

response_model defines the public shape of the response independent of the internal object returned. FastAPI filters out fields not in the model, so a stored password never leaks to the client. The same model also powers the auto-generated OpenAPI schema.

More FastAPI Snippets