前言
- 上一篇講了可以為查詢參數添加額外的校驗和元數據,Query 庫:https://www.cnblogs.com/poloyy/p/15306809.html
- 這篇講可以為路徑查詢添加額外的校驗和元數據,Path 庫
Path
可以為路徑參數添加額外的校驗和元數據,跟 Query 的參數是一毛一樣的

元數據
Path 也可以添加元數據相關信息,這些信息將包含在生成的 OpenAPI 中,並由文檔用戶界面和外部工具使用
四種元數據參數
# 別名 alias: Optional[str] = None # 標題 title: Optional[str] = None # 描述 description: Optional[str] = None # 是否棄用 deprecated: Optional[bool] = None
實際代碼
from fastapi import FastAPI, Path from typing import Optional import uvicorn app = FastAPI() # 元數據 @app.get("/items/{item_id}") async def read_items( item_id: Optional[str] = Path( default=..., min_length=2, max_length=50, regex="^菠蘿$", title="標題", description="很長很長的描述", deprecated=True, ) ): return {"item_id": item_id}
校驗成功的請求結果

校驗失敗的請求結果

查看 Swagger API 文檔

重點
- 路徑參數始終是必需的,因為它必須是路徑的一部分
- 所以,Path 的 default 參數值必須設為 ...
元數據不應該使用 alias
因為路徑參數並不能通過 參數名=value 的形式來傳值,所以沒有辦法通過 alias = value 的方式給別名傳值,最終將會報錯
@app.get("/alias/{item_id}") async def read_items( item_id: Optional[str] = Path( default=..., alias="item_alias" ) ): return {"item_id": item_id}
請求結果


查看 Swagger API 文檔,並運行

直接在 Swagger API 文檔上嘗試運行也會報錯,所以路徑參數不要用別名哦!
函數參數排序問題

Python 會將 item_id: int = Path(...) 識別為默認參數,而 q: str 是位置參數,而位置參數不能在默認參數后面,所以爆紅了
解決方案
在 Python 3.8 新除了僅限關鍵字參數:https://www.cnblogs.com/poloyy/p/15106522.html
@app.get("/item/{item_id}") async def read_items( *, item_id: int = Path(...), name: str): return {"item_id": item_id, "name": name}
將 * 作為第一個參數,那么 * 后面的所有參數都會當做關鍵字參數處理,即使它們沒有設置默認值(像 name)
正常傳參的請求結果

數字類型校驗
Query 和 Path 都可以添加數字校驗,Query 文章並沒有講解數字校驗,所以這里重點講下
數字校驗參數
# 大於 gt: Optional[float] = None # 大於等於 ge: Optional[float] = None # 小於 lt: Optional[float] = None # 小於等於 le: Optional[float] = None
實際代碼
@app.get("/number/{item_id}") async def read_items( *, item_id: int = Path(..., title="The IDsss", gt=10, le=20), name: str = None): return {"item_id": item_id, "name": name}
校驗成功的請求結果

校驗失敗的請求結果

Query 和 Path 綜合使用
@app.get("/path_query/{item_id}") async def read_items( *, item_id: int = Path(..., description="path", ge=1, lt=5, example=1), name: str, age: float = Query(..., description="query", gt=0.0, le=10)): return {"item_id": item_id, "age": age, "name": name}
正確傳參的請求結果

注意
數字校驗也可以適用於 float 類型的值
查看 Swagger API 文檔

這里的 item_id 還加了個 example 參數,就是個示例值,所以在接口文檔中會顯示 Example
總結
- Query、Path 和后面會講到的 Form、Cookie...等等,都是公共 Param 類的子類,但實際開發中並不會直接使用 Param 類
- 所有這些子類都共享相同的額外校驗參數和元數據
Query 類

Path 類

Param 類

