Automated Action b5638b4c86 Add Simple Todo Application with FastAPI and SQLite
- Create project structure with FastAPI setup
- Implement Todo model with SQLAlchemy
- Set up database migrations with Alembic
- Create CRUD API endpoints for Todo items
- Add health endpoint for application monitoring
- Update README with documentation

generated with BackendIM... (backend.im)
2025-05-13 05:10:03 +00:00

103 lines
2.4 KiB
Python

from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app import schemas
from app.models.todo import Todo
from app.db.session import get_db
router = APIRouter()
@router.get("/", response_model=List[schemas.Todo])
def read_todos(
db: Session = Depends(get_db),
skip: int = 0,
limit: int = 100,
) -> Any:
"""
Retrieve todos.
"""
todos = db.query(Todo).order_by(Todo.created_at.desc()).offset(skip).limit(limit).all()
return todos
@router.post("/", response_model=schemas.Todo, status_code=status.HTTP_201_CREATED)
def create_todo(
*,
db: Session = Depends(get_db),
todo_in: schemas.TodoCreate,
) -> Any:
"""
Create new todo.
"""
todo = Todo(
title=todo_in.title,
description=todo_in.description,
completed=todo_in.completed,
)
db.add(todo)
db.commit()
db.refresh(todo)
return todo
@router.get("/{id}", response_model=schemas.Todo)
def read_todo(
*,
db: Session = Depends(get_db),
id: int,
) -> Any:
"""
Get todo by ID.
"""
todo = db.query(Todo).filter(Todo.id == id).first()
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Todo with ID {id} not found"
)
return todo
@router.put("/{id}", response_model=schemas.Todo)
def update_todo(
*,
db: Session = Depends(get_db),
id: int,
todo_in: schemas.TodoUpdate,
) -> Any:
"""
Update a todo.
"""
todo = db.query(Todo).filter(Todo.id == id).first()
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Todo with ID {id} not found"
)
update_data = todo_in.model_dump(exclude_unset=True)
for field, value in update_data.items():
setattr(todo, field, value)
db.add(todo)
db.commit()
db.refresh(todo)
return todo
@router.delete("/{id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_todo(
*,
db: Session = Depends(get_db),
id: int,
) -> Any:
"""
Delete a todo.
"""
todo = db.query(Todo).filter(Todo.id == id).first()
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Todo with ID {id} not found"
)
db.delete(todo)
db.commit()
return None