Automated Action 02e8d8dd3e Create Todo Application with FastAPI and SQLite
- Set up project structure with FastAPI
- Create Todo database model with SQLAlchemy
- Add Alembic migrations
- Implement CRUD API endpoints for todos
- Add health endpoint for application monitoring
- Add README with documentation

generated with BackendIM... (backend.im)
2025-05-14 00:44:49 +00:00

94 lines
2.3 KiB
Python

from typing import List, Any, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.db.session import get_db
from app.models.todo import Todo
from app.schemas.todo import TodoCreate, TodoUpdate, Todo as TodoSchema
router = APIRouter()
@router.get("/", response_model=List[TodoSchema])
def read_todos(
skip: int = 0, limit: int = 100, db: Session = Depends(get_db)
) -> Any:
"""
Retrieve todos.
"""
todos = db.query(Todo).offset(skip).limit(limit).all()
return todos
@router.post("/", response_model=TodoSchema, status_code=status.HTTP_201_CREATED)
def create_todo(*, db: Session = Depends(get_db), todo_in: 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("/{todo_id}", response_model=TodoSchema)
def read_todo(*, db: Session = Depends(get_db), todo_id: int) -> Any:
"""
Get todo by ID.
"""
todo = db.query(Todo).filter(Todo.id == todo_id).first()
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Todo not found"
)
return todo
@router.put("/{todo_id}", response_model=TodoSchema)
def update_todo(
*,
db: Session = Depends(get_db),
todo_id: int,
todo_in: TodoUpdate,
) -> Any:
"""
Update a todo.
"""
todo = db.query(Todo).filter(Todo.id == todo_id).first()
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Todo not found"
)
update_data = todo_in.dict(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("/{todo_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_todo(*, db: Session = Depends(get_db), todo_id: int) -> Any:
"""
Delete a todo.
"""
todo = db.query(Todo).filter(Todo.id == todo_id).first()
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Todo not found"
)
db.delete(todo)
db.commit()
return None