Perform SQLAlchemy CRUD operations with FastAPI — create, read, update, and delete patterns.
SQLAlchemy ORM with FastAPI
from sqlalchemy import create_engine, Column, Integer, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
from datetime import datetime
DATABASE_URL = "postgresql://user:pass@localhost/mydb"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
class Post(Base):
__tablename__ = "posts"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, nullable=False)
body = Column(String, nullable=False)
created_at = Column(DateTime, default=datetime.utcnow)
Base.metadata.create_all(bind=engine)
# CRUD operations
@app.get("/posts/{id}")
def get_post(id: int, db: Session = Depends(get_db)):
post = db.query(Post).filter(Post.id == id).first()
if not post:
raise HTTPException(404, "Post not found")
return post
@app.post("/posts", status_code=201)
def create_post(data: PostCreate, db: Session = Depends(get_db)):
post = Post(**data.model_dump())
db.add(post)
db.commit()
db.refresh(post)
return post