- 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 - 響應模型
一個操作函式返回一個 JSON 響應給客戶端。響應可以是 Python 基本型別,例如數字、字串、列表或字典等。它也可以是 Pydantic 模型的形式。為了使函式返回模型物件,操作裝飾器應該宣告一個 **response_model** 引數。
藉助 response_model,FastAPI 將輸出資料轉換為模型類的結構。它驗證資料,並在 OpenAPI 路徑操作中新增 JSON Schema 以進行響應。
response_model 引數的一個重要優勢是,我們可以透過從模型中選擇欄位來格式化輸出,將響應轉換為輸出模型。
示例
在下面的示例中,POST 操作裝飾器以 student 類(BaseModel 的子類)的物件形式接收請求體。由於此類中的一個欄位,即 marks(分數列表)在響應中不需要,因此我們定義了另一個名為 percent 的模型,並將其用作 response_model 引數。
from typing import List
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class student(BaseModel):
id: int
name :str = Field(None, title="name of student", max_length=10)
marks: List[int] = []
percent_marks: float
class percent(BaseModel):
id:int
name :str = Field(None, title="name of student", max_length=10)
percent_marks: float
@app.post("/marks", response_model=percent)
async def get_percent(s1:student):
s1.percent_marks=sum(s1.marks)/2
return s1
如果我們檢查 Swagger 文件,它會顯示“/marks”路由獲取 student 類物件作為請求體。用適當的值填充屬性並執行 **get_percent()** 函式。
伺服器響應被轉換為 percent 類,因為它已被用作 response_model。
廣告