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