FastAPI - CRUD 操作



REST 架構使用 HTTP 動詞或方法對資源進行操作。POST、GET、PUT 和 DELETE 方法分別執行建立、讀取、更新和刪除操作。

在下面的示例中,我們將使用 Python 列表作為記憶體資料庫並在其上執行 CRUD 操作。首先,讓我們設定一個 FastAPI 應用物件並宣告一個名為 Book 的 Pydantic 模型。

from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
data = []
class Book(BaseModel):
   id: int
   title: str
   author: str
   publisher: str

使用 @app.post() 裝飾器填充此模型的物件,並將其追加到書籍列表中(宣告書籍列表的資料)。

@app.post("/book")
def add_book(book: Book):
   data.append(book.dict())
   return data

在 Swagger UI 中,執行此操作函式幾次並新增一些資料。

FastAPI CRUD Operations

伺服器的 JSON 響應顯示了迄今為止新增的書籍列表。

FastAPI CRUD Operations

要檢索列表,請定義一個繫結到 @app.get() 裝飾器的操作函式,如下所示:

@app.get("/list")
def get_books():
   return data

要檢索具有其 id 作為路徑引數的書籍,請定義 get() 操作裝飾器和 get_book() 函式,如下所示:

@app.get("/book/{id}")
def get_book(id: int):
   id = id - 1
   return data[id]

/list 路由檢索所有書籍。

FastAPI CRUD Operations

另一方面,在“/book/1”路由中使用“id”作為路徑引數。

FastAPI CRUD Operations

將檢索 id=1 的書籍,這可以在 Swagger UI 的伺服器響應中看到。

FastAPI CRUD Operations

接下來,定義 @app.put() 裝飾器,該裝飾器修改資料列表中的物件。此裝飾器也為 id 欄位提供路徑引數。

@app.put("/book/{id}")
def add_book(id: int, book: Book):
   data[id-1] = book
   return data

在 Swagger UI 中檢查此操作函式。將 id 設定為 1,並在請求體中將釋出者的值更改為 BPB。

FastAPI CRUD Operations

執行後,響應顯示列表中 id=1 的物件已更新為新值。

FastAPI CRUD Operations

最後,我們定義 @app.delete() 裝飾器以刪除與路徑引數對應的物件。

@app.delete("/book/{id}")
def delete_book(id: int):
   data.pop(id-1)
   return data

將 id 設定為 1 作為路徑引數並執行函式。

FastAPI CRUD Operations

執行後,列表現在僅顯示兩個物件。

FastAPI CRUD Operations
廣告

© . All rights reserved.