系列文章:
FastAPI 學習之路(一)fastapi--高性能web開發框架
請求體有多個參數如何處理?
別的不多說,我們先寫一個需求,然后演示下如何展示。
需求:寫一個接口,傳遞以下參數,書本的名稱,描述,價格,打折。
接口返回返回最后的價格
我們去看下代碼如何實現
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None @app.put("/items") def update_item(item: Optional[Item]): result={} if item.tax is not None: total=item.price*item.tax result['price'] = total result['name']=item.name return result result['price'] = item.price result['name'] = item.name return result
那么我們測試下,最后是否實現了這個功能,當我們輸入所有的參數的時候。

最后是在我們實際的打折上返回的。
那么我們看下,我們不增加打折如何返回

沒有打折就原價返回了名稱和價格。
如果默認給了None或者其他內容,這個參數就是可以選擇增加或者不增加。但是沒有給默認值的時候,就是必須傳遞的,否則會返回對應的錯誤,我們可以看下。假如我們不傳遞價格。

我們可以看到沒有默認值的參數就是一個必須的。不然接口會返回對應的錯誤。
除了聲明以上單個的,我們還可以聲明多個請求體參數,比如我們可以在之前的需求,增加一個返回,要求返回作者,和作者的朝代。如何實現呢。
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None class User(BaseModel): username: str year: str @app.put("/items") async def update_item(item: Optional[Item],user:User): result={} if item.tax is not None: total=item.price*item.tax result['price'] = total result['name']=item.name result['user']=user return result result['price'] = item.price result['name'] = item.name result['user']=user return result
那么我們看下接口的請求

當我們增加打折。看下返回結果

我們可以看下接口的返回。
FastAPI 將自動對請求中的數據進行轉換,因此 item 參數將接收指定的內容,user 參數也是如此。
我們要想在增加一個鍵,在哪里出售,但是要作為請求體的另一個鍵進行處理,如何 實現呢
from typing import Optional from fastapi import FastAPI,Body from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None class User(BaseModel): username: str year: str @app.put("/items") async def update_item(item: Optional[Item],user:User,sell:str=Body(...)): result={} if item.tax is not None: total=item.price*item.tax result['price'] = total result['name']=item.name result['user']=user result['sell']=sell return result result['price'] = item.price result['name'] = item.name result['user']=user result['sell'] = sell return result
我們可以看到如下

假如我們把參數放在查詢內,返回錯誤

參數必須放在body內請求。
文章首發在公眾號,歡迎關注。

