CRUD Operations in Python

From the FastAPI cheat sheet ยท Database Integration ยท verified Jul 2026

CRUD Operations

Create, read, update, and delete records with SQLAlchemy.

python
from fastapi import Depends
from sqlalchemy.orm import Session

@app.post("/items/", response_model=ItemOut, status_code=201)
def create_item(item: ItemCreate, db: Session = Depends(get_db)):
    db_item = Item(**item.model_dump())
    db.add(db_item)
    db.commit()
    db.refresh(db_item)
    return db_item
๐Ÿ’ก Use model_dump(exclude_unset=True) for PATCH-style partial updates
โšก db.refresh() reloads the object from the DB โ€” gets auto-generated fields like id
๐Ÿ“Œ Always check if the record exists before updating/deleting โ€” raise 404 if not
๐ŸŸข Use sync def (not async def) for SQLAlchemy โ€” it uses blocking I/O by default
cruddatabasesqlalchemy

More Python tasks

Back to the full FastAPI cheat sheet