FastAPI 路由詳解:路徑參數、查詢參數、請求體,一篇掌握!
你是否曾在編寫接口時對參數處理感到迷糊?
- 路徑參數怎么寫?
- 查詢參數和請求體參數有啥區別?
- 怎么自動類型校驗、生成文檔?
這篇文章將帶你全面掌握 FastAPI 中最常用的三種參數類型,配合 Pydantic 驗證,輕松構建高質量 API!
路徑參數(Path Parameters)
路徑參數出現在 URL 中,例如 /users/{user_id}。
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}")
def get_user(user_id: int):
return {"user_id": user_id}
訪問 /users/123,FastAPI 會自動將 123 轉為 int 傳入 user_id。
特點:
- 參數寫在 URL 路徑中
- 自動類型轉換
- 常用于資源定位(如用戶 ID)
查詢參數(Query Parameters)
查詢參數通過 URL ? 后的鍵值對傳遞,例如 /search?q=fastapi&limit=10。
@app.get("/search")
def search(q: str, limit: int = 10):
return {"query": q, "limit": limit}
訪問 /search?q=fastapi&limit=5 返回:
{"query": "fastapi", "limit": 5}
特點:
- 傳參方式靈活,可設置默認值
- 自動類型校驗、自動文檔支持
- 常用于分頁、篩選、搜索
請求體參數(Request Body)
當你需要傳遞 JSON 對象等復雜結構,就要用請求體參數,并結合 Pydantic 定義模型。
步驟一:定義數據模型
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
tags: list[str] = []
步驟二:接收請求體
@app.post("/items/")
def create_item(item: Item):
return item
發送請求:
POST /items/
{
"name": "iPhone 15",
"price": 999.9,
"tags": ["phone", "apple"]
}
FastAPI 會:
- 自動將 JSON 轉換為對象
- 自動校驗字段
- 自動生成 API 文檔
混合使用(路徑 + 查詢 + 請求體)
三種參數可以組合使用:
from typing import Union
@app.put("/items/{item_id}")
def update_item(
item_id: int,
q: Union[str, None] = None,
item: Item = None
):
return {
"item_id": item_id,
"q": q,
"item": item
}
參數驗證與文檔增強
FastAPI 支持通過 Query 和 Path 設置限制和文檔描述:
from fastapi import Query, Path
@app.get("/products/{product_id}")
def get_product(
product_id: int = Path(..., title="產品 ID", ge=1),
keyword: str = Query(None, max_length=20, description="搜索關鍵詞")
):
return {"product_id": product_id, "keyword": keyword}
支持的驗證包括:
- 是否必填(...)
- 數值范圍(ge=1)
- 字符長度(max_length)
- 自動展示在 Swagger 文檔中
總結
類型 | 來源 | 適用場景 | 特點 |
路徑參數 | /users/{id} | 標識資源 | 自動轉換類型、資源定位 |
查詢參數 | ?q=xxx&limit=1 | 篩選分頁搜索 | 可選默認值、自動文檔 |
請求體參數 | JSON 請求體 | 提交復雜結構數據 | 使用 Pydantic 模型驗證解析 |
FastAPI 的參數處理不僅強大,還智能、自動、文檔友好,大大提升開發體驗和效率!