# main.py
# A complete, runnable example of a REST API using FastAPI and SQLAlchemy (SQLite database).
# Features full CRUD operations for "Todos".
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy import create_engine, Column, Integer, String, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
from pydantic import BaseModel
from typing import List
# Database setup (SQLite for simplicity)
SQLALCHEMY_DATABASE_URL = "sqlite:///./todos.db" # Persistent file; use "sqlite:///:memory:" for in-memory
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
# SQLAlchemy Model
class Todo(Base):
__tablename__ = "todos"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
description = Column(String, nullable=True)
completed = Column(Boolean, default=False)
# Create tables
Base.metadata.create_all(bind=engine)
# Pydantic Schemas
class TodoBase(BaseModel):
title: str
description: str | None = None
class TodoCreate(TodoBase):
pass
class TodoUpdate(TodoBase):
completed: bool | None = None
class Todo(TodoBase):
id: int
completed: bool
class Config:
from_attributes = True
# FastAPI App
app = FastAPI(title="Todo API", description="A simple CRUD API with FastAPI + SQLAlchemy")
# Dependency to get DB session
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# CRUD Endpoints
@app.post("/todos/", response_model=Todo, status_code=201)
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
db_todo = Todo(**todo.model_dump())
db.add(db_todo)
db.commit()
db.refresh(db_todo)
return db_todo
@app.get("/todos/", response_model=List[Todo])
def read_todos(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
todos = db.query(Todo).offset(skip).limit(limit).all()
return todos
@app.get("/todos/{todo_id}", response_model=Todo)
def read_todo(todo_id: int, db: Session = Depends(get_db)):
todo = db.query(Todo).filter(Todo.id == todo_id).first()
if todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
return todo
@app.put("/todos/{todo_id}", response_model=Todo)
def update_todo(todo_id: int, todo_update: TodoUpdate, db: Session = Depends(get_db)):
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
update_data = todo_update.model_dump(exclude_unset=True)
for field, value in update_data.items():
setattr(db_todo, field, value)
db.commit()
db.refresh(db_todo)
return db_todo
@app.delete("/todos/{todo_id}", status_code=204)
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
db.delete(db_todo)
db.commit()
return None
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
Setup Instructions
-
Install dependencies:
pip install fastapi sqlalchemy uvicorn[standard] pydantic[email-validator]
-
Run the API:
uvicorn main:app --reload --host 0.0.0.0 --port 8000
- Or run directly:
python main.py
-
Interactive API Docs:
Example Usage
- Create Todo:
POST /todos/ with {"title": "Buy groceries", "description": "Milk and bread"}
- List Todos:
GET /todos/?skip=0&limit=10
- Get Todo:
GET /todos/1
- Update Todo:
PUT /todos/1 with {"title": "Updated", "completed": true}
- Delete Todo:
DELETE /todos/1
Key Features
- Full CRUD: Create, Read (single/list), Update, Delete.
- Session Management: Per-request DB sessions with
Depends(get_db).
- Validation: Pydantic models for request/response.
- Error Handling: 404 for missing resources.
- Async-Friendly: FastAPI handles it; SQLAlchemy is sync here (fine for SQLite).
- Persistent DB:
./todos.db file created automatically.
This is production-ready for a simple app. Scale by switching to PostgreSQL/MySQL (SQLALCHEMY_DATABASE_URL = "postgresql://user:pass@localhost/dbname") and adding Alembic for migrations.