# pydantic-type-mismatch-pattern - Author: lijt - Repository: kofttlcc/stls - Version: 20260206163149 - Stars: 0 - Forks: 0 - Last Updated: 2026-02-06 - Source: https://github.com/kofttlcc/stls - Web: https://mule.run/skillshub/@@kofttlcc/stls~pydantic-type-mismatch-pattern:20260206163149 --- --- name: pydantic-type-mismatch-pattern category: 02-troubleshooting created_at: 2026-01-18 17:32:48 status: experimental trigger: manual --- # pydantic-type-mismatch-pattern # Pydantic 模型類型與實際返回值不匹配 ## 問題描述 FastAPI 路由返回 Pydantic 模型時,如果實際返回的數據類型與模型定義不匹配,會拋出 500 Internal Server Error。 ## 常見場景 - 模型定義 `data: Dict[str, Any]` 但代碼返回 `[]`(空列表) - 模型定義 `data: List[str]` 但代碼返回 `{}`(空字典) ## 錯誤日誌特徵 ``` pydantic_core._pydantic_core.ValidationError: 1 validation error for [ModelName] data Input should be a valid dictionary [type=dict_type, input_value=[], input_type=list] ``` ## 解決方案 ### 方案 A:使用 `Any` 類型(靈活但弱類型) ```python from typing import Any class FeatureResponse(BaseModel): data: Any # 接受任何類型 ``` ### 方案 B:使用 `Union` 聯合類型(推薦) ```python from typing import Union, List, Dict class FeatureResponse(BaseModel): data: Union[List[Dict[str, Any]], Dict[str, Any]] = [] ``` ### 方案 C:統一代碼返回類型 確保所有代碼路徑返回一致的類型: ```python # 正確做法:都返回 List return FeatureResponse(data=records if records else []) # 錯誤做法:有時返回 Dict,有時返回 List ``` ## 最佳實踐 1. **審計時重點檢查**:`except` 分支中的返回類型是否與正常路徑一致 2. **優雅降級**:空數據應返回空集合(`[]` 或 `{}`)而非 `None` 3. **類型一致性**:API 響應結構應在所有情況下保持一致