- 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 - 請求體
現在我們將使用 Pydantic 模型物件作為客戶端請求的請求體。如前所述,我們需要為此使用 POST 操作裝飾器。
import uvicorn
from fastapi import FastAPI
from typing import List
from pydantic import BaseModel, Field
app = FastAPI()
class Student(BaseModel):
id: int
name :str = Field(None, title="name of student", max_length=10)
subjects: List[str] = []
@app.post("/students/")
async def student_data(s1: Student):
return s1
可以看到,student_data() 函式用@app.post() 裝飾器裝飾,該裝飾器的 URL 端點為 "/students/"。它從客戶端的請求中接收 Student 類的物件作為 Body 引數。要測試此路由,請啟動 Uvicorn 伺服器並在瀏覽器中訪問 https://:8000/docs 開啟 Swagger UI 文件。
文件識別出 "/students/" 路由與student_data() 函式以及 POST 方法相關聯。在 schemas 部分,將列出 Student 模型。
展開其前面的節點以顯示模型的結構。
點選“試一試”按鈕在請求體中填寫測試值。
點選“執行”按鈕獲取伺服器的響應值。
雖然 Pydantic 模型會自動填充請求體,但也可以使用單個值向其新增屬性。為此,我們需要將 Body 類物件用作要裝飾的操作函式的引數。
首先,我們需要從fastapi匯入 Body 類。如下例所示,在@app.post() 裝飾器下方,在student_data() 函式的定義中宣告 'name' 和 'marks' 作為 Body 引數。
import uvicorn
from fastapi import FastAPI, Body
@app.post("/students")
async def student_data(name:str=Body(...),
marks:int=Body(...)):
return {"name":name,"marks": marks}
如果我們檢查 Swagger UI 文件,我們應該能夠找到與 student_data() 函式關聯的此 POST 方法,並且該方法具有包含兩個引數的請求體。
還可以宣告一個操作函式,使其除了請求體之外,還具有路徑和/或查詢引數。讓我們修改 student_data() 函式,使其具有路徑引數 'college'、查詢引數 'age' 和一個 Student 模型物件作為主體引數。
@app.post("/students/{college}")
async def student_data(college:str, age:int, student:Student):
retval={"college":college, "age":age, **student.dict()}
return retval
該函式新增 college 和 age 引數的值以及 Student 物件的字典表示形式,並將其作為響應返回。我們可以如下檢查 API 文件:-
可以看到,college 是路徑引數,age 是查詢引數,而Student 模型是請求體。