一文帶你搞懂Python?FastAPI中所有核心參數(shù)的設(shè)置
本文帶你一次搞懂 FastAPI 中的所有核心參數(shù)類型:從簡單的查詢字符串(?name=value),到定義URL片段的路徑參數(shù),再到處理復(fù)雜 JSON 或表單數(shù)據(jù)的請求體。重點深入 Pydantic BaseModel,教你如何用它優(yōu)雅地定義、驗證和組織復(fù)雜數(shù)據(jù),并自動生成 API 文檔。讀完你就能清晰地規(guī)劃 API 的數(shù)據(jù)接口了。
查詢參數(shù)與路徑參數(shù):地基要打牢
這是兩種最基礎(chǔ)、最常用的參數(shù),都直接體現(xiàn)在 URL 中。
查詢參數(shù)(Query Parameters):跟在 URL 問號?后面,格式為key1=value1&key2=value2。在 FastAPI 中,函數(shù)參數(shù)不是路徑的一部分的,默認(rèn)就是查詢參數(shù)。
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 10):
# `skip`和`limit`就是查詢參數(shù),如:/items/?skip=20&limit=5
return {"skip": skip, "limit": limit}使用 skip: int = 0 形式,就定義了帶默認(rèn)值的可選參數(shù)。如果沒有默認(rèn)值(如 name: str),它就是必需的查詢參數(shù)。
路徑參數(shù)(Path Parameters):直接是 URL 路徑的一部分,用花括號{}聲明。通常用于唯一標(biāo)識資源,比如根據(jù)ID獲取某篇文章。
@app.get("/items/{item_id}")
async def read_item(item_id: int): # item_id 是路徑參數(shù)
return {"item_id": item_id}注意它們的順序!如果把 /items/{item_id} 和 /items/me 兩個端點都定義,要把具體的路徑(/items/me)放在前面,否則me會被當(dāng)成item_id的值。
請求體參數(shù):處理復(fù)雜數(shù)據(jù)
當(dāng)你需要客戶端發(fā)送較多數(shù)據(jù)(如創(chuàng)建新文章)時,就需要請求體。FastAPI 用 Body(), Form() 等工具函數(shù)來聲明。
JSON 請求體(Body):最常見的 REST API 數(shù)據(jù)格式。使用 Pydantic 的 BaseModel 是最佳實踐(下文詳解),也可用 Body() 直接聲明多個參數(shù)。
from fastapi import Body
@app.put("/items/{item_id}")
async def update_item(
item_id: int,
name: str = Body(...), # Body(...) 表示必需項
description: str = Body(None) # Body(None) 表示可選項
):
return {"item_id": item_id, "name": name, "description": description}表單數(shù)據(jù)(Form):當(dāng)數(shù)據(jù)來自 HTML 表單或需要上傳文件時使用。如何要上傳大文件,需要先安裝 python-multipart。
from fastapi import Form
@app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)):
return {"username": username}混合參數(shù):自由組合,各司其職
FastAPI 能智能地區(qū)分參數(shù)來源,你可以同時使用路徑、查詢和請求體參數(shù)。
from fastapi import Path, Query, Body
@app.put("/mixed-items/{item_id}")
async def update_mixed_item(
*,
item_id: int = Path(..., title="商品ID", ge=1), # 路徑參數(shù),>=1
q: str = Query(None, alias="query-string"), # 可選查詢參數(shù),別名
item: dict = Body(...) # 必需的JSON請求體
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
results.update({"item": item})
return results這里用到了參數(shù)校驗:ge=1 表示值大于等于1。Query, Path, Body 等函數(shù)讓聲明更明確且功能更強大(如添加描述、別名、校驗)。
結(jié)構(gòu)化利器:Pydantic BaseModel
這是 FastAPI 的靈魂特性之一。 BaseModel 讓你用 Python 類來定義數(shù)據(jù)模型,它自動處理數(shù)據(jù)驗證、序列化和文檔生成。
from pydantic import BaseModel, EmailStr
from typing import Optional, List
class UserCreate(BaseModel):
# 必需字段
username: str
email: EmailStr # 內(nèi)置郵箱格式驗證
# 可選字段,帶默認(rèn)值
full_name: Optional[str] = None
# 列表類型
tags: List[str] = []
@app.post("/users/")
async def create_user(user: UserCreate): # 一個參數(shù)接管整個請求體
# 直接訪問已驗證好的數(shù)據(jù)
if user.full_name:
greeting = f"Hello, {user.full_name}!"
else:
greeting = f"Hello, {user.username}!"
return {"message": greeting, "user_info": user.dict()}BaseModel 的優(yōu)勢:
- 聲明即驗證: 字段類型不對、郵箱格式錯誤等會自動返回 422 錯誤。
- 自動文檔: Swagger UI 和 ReDoc 會自動顯示模型結(jié)構(gòu)和示例。
- 代碼清晰: 數(shù)據(jù)契約明確,業(yè)務(wù)邏輯與數(shù)據(jù)驗證分離。
- 嵌套自由: 模型可以嵌套其他模型,輕松處理復(fù)雜數(shù)據(jù)。
完整代碼示例
下面是一個融合了主要參數(shù)類型的實戰(zhàn)示例,你可以直接復(fù)制運行。
from fastapi import FastAPI, Path, Query, Body
from pydantic import BaseModel
from typing import Optional
from datetime import datetime
app = FastAPI(title="參數(shù)詳解示例")
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float = Body(..., gt=0)
tax: Optional[float] = None
tags: list = []
@app.post("/advanced-items/{category}")
async def create_advanced_item(
category: str = Path(..., description="物品分類"),
item_id: int = Query(..., ge=1, description="物品ID"),
q: Optional[str] = Query(None, max_length=50),
urgent: bool = Query(False),
item: Item = Body(..., example={ # 為文檔提供示例
"name": "Foo",
"price": 50.5,
"tags": ["cool", "new"]
})
):
"""創(chuàng)建新物品的復(fù)雜端點"""
total = item.price + (item.tax if item.tax else 0)
result = {
"category": category,
"item_id": item_id,
"query_string": q,
"urgent": urgent,
"item_name": item.name,
"total_price": total,
"created_at": datetime.now().isoformat()
}
return result
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)運行后,訪問 http://127.0.0.1:8000/docs,你將看到一個功能齊全的交互式 API 文檔,所有參數(shù)和模型都清晰可見。
到此這篇關(guān)于一文帶你搞懂Python FastAPI中所有核心參數(shù)的設(shè)置的文章就介紹到這了,更多相關(guān)Python FastAPI參數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
PyCharm利用pydevd-pycharm實現(xiàn)Python遠程調(diào)試的詳細過程
這篇文章主要介紹了PyCharm利用pydevd-pycharm實現(xiàn)Python遠程調(diào)試,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-09-09
Python獲取命令實時輸出-原樣彩色輸出并返回輸出結(jié)果的示例
今天小編就為大家分享一篇Python獲取命令實時輸出-原樣彩色輸出并返回輸出結(jié)果的示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
Python實現(xiàn)數(shù)據(jù)庫數(shù)據(jù)自動化導(dǎo)出PDF報告
本文將介紹如何使用Python構(gòu)建一個自動化工具,實現(xiàn)從MySQL數(shù)據(jù)庫提取員工數(shù)據(jù),文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-09-09
python uvloop事件循環(huán)庫使用功能示例探究
這篇文章主要為大家介紹了python uvloop事件循環(huán)庫使用功能示例探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01
使用Python實現(xiàn)圖像LBP特征提取的操作方法
LBP特征叫做局部二值模式,常用于紋理特征提取,并在紋理分類中具有較強的區(qū)分能力,本文給大家介紹了如何使用Python實現(xiàn)圖像LBP特征提取的操作方法,需要的朋友可以參考下2025-04-04
pandas中DataFrame.to_dict()的實現(xiàn)示例
本文主要介紹了pandas中DataFrame.to_dict()的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-08-08
Python?ArcPy實現(xiàn)批量對大量遙感影像相減做差
這篇文章主要為大家介紹了如何基于Python中ArcPy模塊實現(xiàn)對大量柵格遙感影像文件批量進行相減做差,文中的示例代碼講解詳細,感興趣的可以了解一下2023-06-06

