Automated Action d667651110 Create simple Todo app with FastAPI and SQLite
- Add CRUD operations for todos (create, read, update, delete)
- Implement SQLAlchemy models and schemas
- Set up Alembic for database migrations
- Add health endpoint and CORS configuration
- Include comprehensive API documentation
- Structure project with proper separation of concerns
2025-06-19 22:02:18 +00:00

57 lines
1.8 KiB
Python

from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.db.session import get_db
from app.models.todo import Todo as TodoModel
from app.schemas.todo import Todo, TodoCreate, TodoUpdate
router = APIRouter()
@router.post("/", response_model=Todo)
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
db_todo = TodoModel(**todo.dict())
db.add(db_todo)
db.commit()
db.refresh(db_todo)
return db_todo
@router.get("/", response_model=List[Todo])
def read_todos(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
todos = db.query(TodoModel).offset(skip).limit(limit).all()
return todos
@router.get("/{todo_id}", response_model=Todo)
def read_todo(todo_id: int, db: Session = Depends(get_db)):
todo = db.query(TodoModel).filter(TodoModel.id == todo_id).first()
if todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
return todo
@router.put("/{todo_id}", response_model=Todo)
def update_todo(todo_id: int, todo_update: TodoUpdate, db: Session = Depends(get_db)):
todo = db.query(TodoModel).filter(TodoModel.id == todo_id).first()
if todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
update_data = todo_update.dict(exclude_unset=True)
for field, value in update_data.items():
setattr(todo, field, value)
db.commit()
db.refresh(todo)
return todo
@router.delete("/{todo_id}")
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
todo = db.query(TodoModel).filter(TodoModel.id == todo_id).first()
if todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
db.delete(todo)
db.commit()
return {"message": "Todo deleted successfully"}