什麼是回應模型?
回應模型 (Response Model) 是基於 Pydantic 定義的資料規格,用於限制、過濾及格式化 API 回傳給前端的資料。簡單來說,當後端從資料庫取出原始資料後,回應模型會自動過濾掉敏感或不需要的欄位(例如密碼),僅將符合規格的資料交給客戶端。
回應模型基礎應用
- 定義模型:繼承 pydantic.BaseModel 來定義回傳的資料欄位與型別。
- 套用模型:在路徑裝飾器中使用 response_model 參數指定模型,例如。 @app.get("/", response_model=UserResponse)。
- 處理列表:如果 API 回傳多筆資料,使用 list[ModelName] 作為型別。
- 過濾預設值:使用 response_model_exclude_none=True 可以略過未賦值的欄位。
- ORM 支援:若回傳資料來自資料庫物件(例如 SQLAlchemy),需在 Pydantic 模型配置 from_attributes=True。
from fastapi import FastAPI
from pydantic import BaseModel, ConfigDict, EmailStr # pip install pydantic[email]
from typing import Optional
app = FastAPI()
# 1. 模擬資料庫模型
class UserData:
def __init__(self, id: int, username: str, email: str, password_hash: str, introduce: str = None):
self.id = id
self.username = username
self.email = email
self.password_hash = password_hash
self.introduce = introduce
# 2. 定義回應模型
class UserResponse(BaseModel):
id: int
username: str
email: EmailStr
introduce: Optional[str] = None
model_config = ConfigDict(from_attributes=True)
# 模擬資料庫查詢
def get_user_from_db():
return UserData(
id=1,
username="developer_tw",
email="dev@example.com",
password_hash="secret_hash_value_123",
introduce="Python 愛好者"
)
@app.get("/user/me", response_model=UserResponse)
async def read_current_user():
user = get_user_from_db()
return user
@app.get("/users", response_model=list[UserResponse], response_model_exclude_none=True)
async def read_users():
# user1: introduce 有值 -> JSON 顯示 introduce
user1 = get_user_from_db()
# user2: introduce 為 None -> JSON 自動移除 introduce 欄位
user2 = UserData(2, "taipei_coder", "tp@example.com", "hash_456")
return [user1, user2]












