Automated Action 8ffce8f5fe Implement todo application with FastAPI and SQLite
- Set up project structure with FastAPI
- Create SQLite database models with SQLAlchemy
- Implement Alembic for migrations
- Create API endpoints for todo operations
- Add health check endpoint
- Update README.md with comprehensive documentation

generated with BackendIM... (backend.im)
2025-05-13 04:46:37 +00:00

53 lines
1.9 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from app.db.session import get_db
from app.models.todo import Todo
from app.schemas.todo import TodoCreate, TodoUpdate, TodoResponse
todo_router = APIRouter(prefix="/api/todos", tags=["todos"])
@todo_router.post("/", response_model=TodoResponse, status_code=status.HTTP_201_CREATED)
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
@todo_router.get("/", response_model=List[TodoResponse])
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
@todo_router.get("/{todo_id}", response_model=TodoResponse)
def read_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")
return db_todo
@todo_router.put("/{todo_id}", response_model=TodoResponse)
def update_todo(todo_id: int, todo: 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")
todo_data = todo.model_dump(exclude_unset=True)
for key, value in todo_data.items():
setattr(db_todo, key, value)
db.commit()
db.refresh(db_todo)
return db_todo
@todo_router.delete("/{todo_id}", status_code=status.HTTP_204_NO_CONTENT)
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