
- FastAPI 教程
- FastAPI - 首頁
- FastAPI - 簡介
- FastAPI - Hello World
- FastAPI - OpenAPI
- FastAPI - Uvicorn
- FastAPI - 型別提示
- FastAPI - IDE 支援
- FastAPI - REST 架構
- FastAPI - 路徑引數
- FastAPI - 查詢引數
- FastAPI - 引數驗證
- FastAPI - Pydantic
- FastAPI - 請求體
- FastAPI - 模板
- FastAPI - 靜態檔案
- FastAPI - HTML 表單模板
- FastAPI - 訪問表單資料
- FastAPI - 上傳檔案
- FastAPI - Cookie 引數
- FastAPI - 頭部引數
- FastAPI - 響應模型
- FastAPI - 巢狀模型
- FastAPI - 依賴項
- FastAPI - CORS
- FastAPI - CRUD 操作
- FastAPI - SQL 資料庫
- FastAPI - 使用 MongoDB
- FastAPI - 使用 GraphQL
- FastAPI - Websockets
- FastAPI - FastAPI 事件處理器
- FastAPI - 掛載子應用
- FastAPI - 中介軟體
- FastAPI - 掛載 Flask 應用
- FastAPI - 部署
- FastAPI 有用資源
- FastAPI - 快速指南
- FastAPI - 有用資源
- FastAPI - 討論
FastAPI - 引數驗證
可以對 URL 的路徑引數和查詢引數應用驗證條件。為了對路徑引數應用驗證條件,需要匯入 Path 類。除了引數的預設值之外,在字串引數的情況下,還可以指定最大和最小長度。
from fastapi import FastAPI, Path app = FastAPI() @app.get("/hello/{name}") async def hello(name:str=Path(...,min_length=3, max_length=10)): return {"name": name}
如果瀏覽器 URL 中包含長度小於 3 或大於 10 的引數,例如 (https://:8000/hello/Tutorialspoint),則會出現相應的錯誤訊息,例如:
{ "detail": [ { "loc": [ "path", "name" ], "msg": "ensure this value has at most 10 characters", "type": "value_error.any_str.max_length", "ctx": { "limit_value": 10 } } ] }
OpenAPI 文件也顯示了應用的驗證:

驗證規則也可以應用於數值引數,使用以下運算子:
gt - 大於
ge - 大於或等於
lt - 小於
le - 小於或等於
讓我們修改上述操作裝飾器,將 age 作為路徑引數並應用驗證。
from fastapi import FastAPI, Path app = FastAPI() @app.get("/hello/{name}/{age}") async def hello(*, name: str=Path(...,min_length=3 , max_length=10), age: int = Path(..., ge=1, le=100)): return {"name": name, "age":age}
在這種情況下,對引數 name 和 age 都應用了驗證規則。如果輸入的 URL 為 https://:8000/hello/hi/110,則 JSON 響應將顯示以下驗證失敗說明:
{ "detail": [ { "loc": [ "path", "name" ], "msg": "ensure this value has at least 3 characters", "type": "value_error.any_str.min_length", "ctx": { "limit_value": 3 } }, { "loc": [ "path", "age" ], "msg": "ensure this value is less than or equal to 100", "type": "value_error.number.not_le", "ctx": { "limit_value": 100 } } ] }
Swagger UI 文件也識別了這些約束。

查詢引數也可以應用驗證規則。您需要將它們指定為 Query 類建構函式的引數的一部分。
讓我們在上述函式中新增一個名為percent的查詢引數,並應用驗證規則 ge=0(即大於或等於 0)和 lt=100(小於或等於 100)
from fastapi import FastAPI, Path, Query @app.get("/hello/{name}/{age}") async def hello(*, name: str=Path(...,min_length=3 , max_length=10), \ age: int = Path(..., ge=1, le=100), \ percent:float=Query(..., ge=0, le=100)): return {"name": name, "age":age}
如果輸入的 URL 為 https://:8000/hello/Ravi/20?percent=79,則瀏覽器將顯示以下 JSON 響應:
{"name":"Ravi","age":20}
FastAPI 正確地識別了 percent 為應用了驗證條件的查詢引數。它在 OpenAPI 文件中反映如下:

雖然客戶端可以使用 GET 方法將路徑和查詢引數傳送到 API 伺服器,但我們需要應用 POST 方法才能將一些二進位制資料作為 HTTP 請求的一部分發送。此二進位制資料可以是任何 Python 類的物件形式。它構成請求體。FastAPI 使用 Pydantic 庫來實現此目的。