在使用FastAPI構建API時,參數處理是核心環節之一。查詢參數(URL問號後的參數)和路徑參數(URL路徑中的參數)是最常見的兩種參數類型。FastAPI提供了Query和Path工具,幫助我們更優雅地處理這些參數的驗證、過濾和文檔生成。本文將通過簡單示例,一步步講解如何用它們實現參數過濾。
一、查詢參數:基礎使用¶
查詢參數是URL中問號?後面的鍵值對,例如 http://example.com/greet?name=Alice&age=25 中的 name 和 age。FastAPI會自動解析這些參數並映射到函數參數上。
示例1:基礎查詢參數
from fastapi import FastAPI
app = FastAPI()
@app.get("/greet")
async def greet(name: str, age: int):
return {"message": f"Hello, {name}! You are {age} years old."}
- 關鍵點:
name: str和age: int是函數參數,FastAPI會自動將URL中的查詢參數轉換爲對應類型(如字符串轉整數)。- 如果不提供
name或age,會直接報錯(參數必填)。 - 測試:訪問
http://localhost:8000/greet?name=Bob&age=20,返回{"message": "Hello, Bob! You are 20 years old."}。
二、用Query處理查詢參數過濾¶
當需要對查詢參數進行驗證、設置默認值或描述時,Query 工具會派上用場。例如限制參數長度、確保數值範圍、設置默認值等。
1. 讓參數可選(設置默認值)¶
如果查詢參數不是必須的,可以通過 Query(None) 設置默認值爲 None,或直接賦值默認值。
示例2:可選查詢參數
from fastapi import Query
@app.get("/greet")
async def greet(
name: str = Query(None, description="你的名字(可選)"), # 設置默認值爲None
age: int = Query(18, description="你的年齡(默認18歲)") # 設置默認值18
):
return {"message": f"Hello, {name or 'Guest'}! You are {age} years old."}
- 關鍵點:
Query(None)表示參數可選(訪問時可不帶該參數)。age: int = Query(18)直接設置默認值,若用戶不提供age,則使用18。- 測試:
- 訪問
http://localhost:8000/greet(不帶參數),返回Hello, Guest! You are 18 years old.。 - 訪問
http://localhost:8000/greet?name=Charlie,返回Hello, Charlie! You are 18 years old.。
2. 參數驗證:限制範圍和格式¶
Query 支持多種驗證規則,例如限制字符串長度、數值範圍、正則表達式等。
示例3:驗證查詢參數
from fastapi import Query
@app.get("/search")
async def search(
keyword: str = Query(
..., # 表示參數必填(必須提供,不允許默認值)
min_length=3, # 字符串最小長度3
max_length=50, # 字符串最大長度50
description="搜索關鍵詞(3-50字符)"
),
page: int = Query(
1, # 默認值1
ge=1, # 大於等於1(ge=greater than or equal)
le=100, # 小於等於100(le=less than or equal)
description="頁碼(1-100)"
)
):
return {"keyword": keyword, "page": page}
- 關鍵點:
...顯式標記參數爲必填(即使未設置默認值,也可強制必填)。min_length/max_length限制字符串長度,ge/le限制數值範圍。- 測試:
- 訪問
http://localhost:8000/search?keyword=abc&page=5,返回正常結果。 - 若
keyword長度爲2(如ab),或page爲0/101,FastAPI會自動返回422錯誤:參數不符合驗證規則。
三、路徑參數:基礎使用¶
路徑參數是URL路徑中固定位置的參數,例如 http://example.com/users/123 中的 123(表示用戶ID)。
示例4:基礎路徑參數
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}")
async def get_user(user_id: int):
return {"user_id": user_id, "message": f"用戶 {user_id} 的信息"}
- 關鍵點:
user_id: int表示路徑參數類型爲整數。- 若訪問
http://localhost:8000/users/abc(非整數),FastAPI會報錯:參數類型錯誤。
四、用Path處理路徑參數過濾¶
與 Query 類似,Path 用於對路徑參數進行類型驗證、範圍過濾和描述設置。
示例5:路徑參數驗證
from fastapi import Path
@app.get("/users/{user_id}")
async def get_user(
user_id: int = Path(
..., # 路徑參數默認必填
gt=0, # 大於0(gt=greater than)
description="用戶ID(必須爲正整數)"
),
name: str = Path(
None, # 可選參數
description="用戶名(可選)"
)
):
return {"user_id": user_id, "name": name or "未提供"}
- 關鍵點:
gt=0確保user_id必須是正整數(若爲負數或0,會驗證失敗)。Path(None)讓name成爲可選路徑參數(若用戶不提供,返回默認值)。- 測試:
- 訪問
http://localhost:8000/users/100,返回{"user_id": 100, "name": "未提供"}。 - 訪問
http://localhost:8000/users/-5(負數ID),FastAPI返回422錯誤:用戶ID必須爲正整數。
五、Query和Path的核心作用¶
- 參數驗證:自動檢查參數類型、範圍、格式,避免非法數據進入業務邏輯。
- 默認值設置:讓參數可選(如
Query(None)),提升接口靈活性。 - 文檔生成:FastAPI自動將參數規則(如長度、範圍)渲染到Swagger UI(訪問
/docs查看),無需手動寫文檔。
總結¶
- 查詢參數用
Query處理,可設置默認值、必填性、長度/範圍驗證等。 - 路徑參數用
Path處理,可限制整數範圍、類型轉換等。 Query和Path不僅簡化了參數過濾邏輯,還通過自動文檔讓API更易用。
通過合理使用這兩個工具,你可以快速構建健壯、易維護的FastAPI接口,讓參數處理更高效。