Database Integration in FastAPI (SQLAlchemy CRUD)
Introduction
So far, we’ve built APIs without storing data.But real-world applications need a database to:
- Store user data.
- Manage products.
- Persist application state.
In this blog, we’ll connect FastAPI with a database using SQLAlchemy and perform CRUD operations.
What is SQLAlchemy?
SQLAlchemy is a powerful Python ORM (Object Relational Mapper) that allows you to:
- Interact with databases using Python code.
- Avoid writing raw SQL queries.
- Work with models instead of tables.
Step 1: Install Dependencies
pip install sqlalchemy
(For SQLite, no extra driver needed)
Project Structure Update
app/├── main.py├── database/│ ├── connection.py├── models/│ ├── item.py├── schemas/│ ├── item.py├── routes/│ ├── item.py
Step 2: Database Connection
app/database/connection.py
from sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmaker, declarative_baseDATABASE_URL = "sqlite:///./test.db"engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})SessionLocal = sessionmaker(bind=engine)Base = declarative_base()
Step 3: Create Model
app/models/item.py
from sqlalchemy import Column, Integer, Stringfrom app.database.connection import Baseclass Item(Base):__tablename__ = "items"id = Column(Integer, primary_key=True, index=True)name = Column(String, index=True)description = Column(String)
Step 4: Create Schema (Pydantic)
app/schemas/item.py
from pydantic import BaseModelclass ItemCreate(BaseModel):name: strdescription: strclass ItemResponse(BaseModel):id: intname: strdescription: strclass Config:orm_mode = True
Step 5: Create Database Tables
Add this in main.py:
from app.database.connection import engine, BaseBase.metadata.create_all(bind=engine)
Step 6: Dependency for DB Session
from app.database.connection import SessionLocalfrom fastapi import Dependsdef get_db():db = SessionLocal()try:yield dbfinally:db.close()Step 7: CRUD Operations
app/routes/item.py1.Create Item
from fastapi import APIRouter, Dependsfrom sqlalchemy.orm import Sessionfrom app.models.item import Itemfrom app.schemas.item import ItemCreatefrom app.database.connection import SessionLocalrouter = APIRouter()def get_db():db = SessionLocal()try:yield dbfinally:db.close()@router.post("/items/")def create_item(item: ItemCreate, db: Session = Depends(get_db)):db_item = Item(name=item.name, descriptRead Items
@router.get("/items/")def get_items(db: Session = Depends(get_db)):return db.query(Item).all()ion=item.description)db.add(db_item)db.commit()db.refresh(db_item)return db_itemUpdate Item
@router.put("/items/{item_id}")def update_item(item_id: int, item: ItemCreate, db: Session = Depends(get_db)):db_item = db.query(Item).filter(Item.id == item_id).first()db_item.name = item.namedb_item.description = item.descriptiondb.commit()return db_itemDelete Item
@router.delete("/items/{item_id}")def delete_item(item_id: int, db: Session = Depends(get_db)):db_item = db.query(Item).filter(Item.id == item_id).first()db.delete(db_item)db.commit()return {"message": "Item deleted"}Step 8: Include Router
main.pyfrom app.routes import itemapp.include_router(item.router)Common Mistakes
1. Forgettingcommit()2. Not usingDepends(get_db)3. Not enablingorm_mode4. Not closing DB sessionBest Practices
1. Use separate files for models, schemas, routes2. Use dependency injection for DB3. Always validate input with schemas4. Handle errors (we’ll improve later)Key Takeaways
- SQLAlchemy connects FastAPI to databases
- Models = DB tables
- Schemas = validation layer
- CRUD operations are easy with ORM
- Dependency injection manages DB sessions
Comments
Post a Comment