Module 9 — Response Models & Data Shaping
In this module, you will learn:
-
Why response models matter
-
How to control what data is returned
-
How to hide fields
-
How to use
response_model_exclude_unset,exclude_none, etc.
1. Basic Response Model
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
id: int
name: str
email: str
@app.get("/users/{user_id}", response_model=User)
def get_user(user_id: int):
return {"id": user_id, "name": "John", "email": "john@example.com"}
Now FastAPI ensures:
-
Fields are correct
-
Types match
-
Extra fields are removed
2. Response Model That Hides Sensitive Fields
class UserDB(User):
password: str
@app.get("/user-safe/{user_id}", response_model=User)
def get_safe_user(user_id: int):
return {"id": user_id, "name": "Ana", "email": "ana@example.com", "password": "secret"}
Even though we returned a password, it will NOT appear.
3. Returning Lists
@app.get("/products", response_model=list[User])
def list_users():
return [
{"id": 1, "name": "A", "email": "a@example.com"},
{"id": 2, "name": "B", "email": "b@example.com"}
]
4. Using response_model_exclude_unset
Useful when you want to hide fields not explicitly set.
@app.get("/partial", response_model=User, response_model_exclude_unset=True)
def partial():
return {"id": 1}
Output:
{"id":1}
5. Excluding or Including Fields
Excluding Fields
@app.get("/exclude", response_model=User, response_model_exclude={"email"})
def exclude_email():
return {"id": 1, "name": "Test", "email": "hide@example.com"}
Including Only Certain Fields
@app.get("/include", response_model=User, response_model_include={"id", "name"})
def include_name_only():
return {"id": 1, "name": "Test", "email": "x@example.com"}
6. Models With Nested Data
class Address(BaseModel):
city: str
country: str
class UserExtended(BaseModel):
id: int
name: str
address: Address
@app.get("/user-details", response_model=UserExtended)
def details():
return {
"id": 1,
"name": "Sam",
"address": {"city": "Chennai", "country": "India"}
}
🎉 Module 9 Complete!
If you want, I can also convert any other module posts to Compose view, or even auto-convert all remaining posts.
No comments:
Post a Comment