FastAPI源碼分析-RequestBody請求體
GET操作不能使用RequestBody,POST/PUT/DELETE/PATCH可以。
RequestBody請求體
請求體使用前,必須要引入pydantic庫中的BaseModel類進行聲明,傳入前創建相應的數據模型
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
return item
數據模型聲明的作用
- 將客戶端的request解析爲JSON
- 將request參數轉換爲相應的數據類型
- 校驗數據類型,如果錯誤返回提示信息
- 將request傳入相應方法
- 數據模型可以複用,並在交互式文檔內顯示
- 編輯器可以根據模型進行類型提示
Path參數+Query參數+RequestBody
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
app = FastAPI()
@app.put("/items/{item_id}")
async def create_item(item_id: int, item: Item, q: str = None):
result = {"item_id": item_id, **item.dict()}
if q:
result.update({"q": q})
return result
參考資料
- FastAPI官網 :https://fastapi.tiangolo.com/
- FastAPI源碼 :https://github.com/tiangolo/fastapi