前面幾天我們把 Pydantic 資料驗證、SQLAlchemy 資料表模型,以及最重要的資料庫依賴注入都準備好了。今天終於要進入重頭戲:CRUD 操作。首先第一步就是新增資料 (Create)。
在寫 API 時,我們通常會建立一個 schemas.py 來專門放 Pydantic 模型,跟 models.py 裡的 SQLAlchemy 模型區分開來。假設我們已經有一個 Pydantic 模型叫做 ItemCreate,負責接收前端傳來的 name, description, price。
現在回到 main.py,我們把新增商品的 API 加上真實的資料庫操作:
from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
import models
from database import engine, SessionLocal
from pydantic import BaseModel
app = FastAPI()
class ItemCreate(BaseModel):
name: str
description: str | None = None
price: float
@app.post("/items/")
def create_item(item: ItemCreate, db: Session = Depends(get_db)):
db_item = models.Item(name=item.name, description=item.description, price=item.price)
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
這四個步驟是 SQLAlchemy 新增資料的標準流程。現在你可以打開 Swagger UI 測試一下,送出請求後,資料就會真真實實地保存在你的 SQLite 資料庫檔案中了!