
FastAPI
Learn the fundamentals of response filtering in FastAPI.
Response filtering automatically excludes specified fields from responses. This is critical for security (hiding passwords, private data) and for providing different response shapes to different clients.
In this section, you'll understand:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class UserFull(BaseModel):
id: int
name: str
email: str
password_hash: str
class UserPublic(BaseModel):
id: int
name: str
email: str
@app.get("/users/{user_id}", response_model=UserPublic)
async def get_user(user_id: int):
# Password hash automatically excluded
return {
"id": user_id,
"name": "John",
"email": "john@example.com",
"password_hash": "xxx" # Won't be sent to client
}class Profile(BaseModel):
ssn: str
phone: str
address: str
class User(BaseModel):
id: int
name: str
profile: Profile
class UserResponse(BaseModel):
id: int
name: str
# profile excluded entirely
@app.get("/profile", response_model=UserResponse)
async def get_profile():
return {
"id": 1,
"name": "John",
"profile": {"ssn": "123-45-6789"} # Not returned
}class Item(BaseModel):
id: int
name: str
internal_cost: float
selling_price: float
@app.get("/items/{item_id}", response_model=Item)
async def get_item(item_id: int):
item = {"id": item_id, "name": "Widget", "internal_cost": 5.00, "selling_price": 9.99}
# Only public fields returned automatically
return itemReady to explore more? Check out the advanced section for production patterns and edge cases.
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward