Ojasa Mirai

Ojasa Mirai

FastAPI

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🚀 Response Model Basics📚 Pydantic Models📚 Nested Responses📚 Response Codes📚 Multiple Responses📚 List Responses📚 Response Filtering📚 Response Documentation
Fastapi/Response Models/Response Filtering

Response Filtering

Learn the fundamentals of response filtering in FastAPI.

🎯 Core Concept

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.

📖 What You'll Learn

In this section, you'll understand:

  • Excluding fields using `response_model` parameter
  • Creating different models for different endpoints
  • Excluding sensitive information (passwords, tokens)
  • Client-specific response shapes
  • Using Pydantic's `Config.fields` for filtering

💡 Simple Example

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
    }

Excluding Nested Fields

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
    }

Dynamic Field Exclusion

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 item

🔑 Key Takeaways

  • ✅ Understand the purpose of response filtering
  • ✅ Know when to apply this pattern
  • ✅ Recognize its benefits in real-world scenarios
  • ✅ Be prepared to use it in your projects

Ready to explore more? Check out the advanced section for production patterns and edge cases.


Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn