Dùng response_model_exclude_unset=True trên decorator của path operation.
FastAPI sẽ serialize model bằng exclude_unset, tức bỏ qua mọi field chưa được gán tường minh khi tạo object.
python
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float = 10.5
@app.get("/items/{item_id}", response_model=Item, response_model_exclude_unset=True)
async def read_item(item_id: str):
return Item(name="Foo", price=50.2)
# response: {"name": "Foo", "price": 50.2}Hai biến thể hay dùng chung:
- response_model_exclude_none=True — bỏ field có giá trị None (khác exclude_unset: field set tường minh bằng None vẫn bị loại).
- response_model_include / response_model_exclude — chọn hoặc loại theo tên field.
Ứng dụng thường gặp: response của PATCH và các API trả về "chỉ phần đã thay đổi", để client phân biệt được "không gửi field này" với "field này bằng null".