Automated Action 5fbf8c4171 Create simple Todo app with FastAPI and SQLite
- Setup project structure with FastAPI
- Create Todo model and database schemas
- Implement CRUD operations for Todo items
- Create API endpoints for Todo operations
- Add health check endpoint
- Configure Alembic for database migrations
- Add detailed documentation in README.md
2025-05-27 16:58:01 +00:00

101 lines
2.5 KiB
Python

from typing import Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Response, status
from sqlalchemy.orm import Session
from app import crud, schemas
from app.db.session import get_db
from app.models.todo import TodoPriority
router = APIRouter()
@router.get("/", response_model=List[schemas.Todo])
def read_todos(
db: Session = Depends(get_db),
skip: int = 0,
limit: int = 100,
priority: Optional[TodoPriority] = None,
completed: Optional[bool] = None,
) -> Any:
"""
Retrieve todos with optional filtering by priority and completion status.
"""
if priority is not None:
todos = crud.todo.get_by_priority(db, priority=priority, skip=skip, limit=limit)
elif completed is not None:
todos = crud.todo.get_completed(db, completed=completed, skip=skip, limit=limit)
else:
todos = crud.todo.get_multi(db, skip=skip, limit=limit)
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 = crud.todo.create(db=db, obj_in=todo_in)
return todo
@router.get("/{todo_id}", response_model=schemas.Todo)
def read_todo(
*,
db: Session = Depends(get_db),
todo_id: int,
) -> Any:
"""
Get todo by ID.
"""
todo = crud.todo.get(db=db, id=todo_id)
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Todo not found",
)
return todo
@router.put("/{todo_id}", response_model=schemas.Todo)
def update_todo(
*,
db: Session = Depends(get_db),
todo_id: int,
todo_in: schemas.TodoUpdate,
) -> Any:
"""
Update a todo.
"""
todo = crud.todo.get(db=db, id=todo_id)
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Todo not found",
)
todo = crud.todo.update(db=db, db_obj=todo, obj_in=todo_in)
return todo
@router.delete("/{todo_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
def delete_todo(
*,
db: Session = Depends(get_db),
todo_id: int,
) -> Response:
"""
Delete a todo.
"""
todo = crud.todo.get(db=db, id=todo_id)
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Todo not found",
)
crud.todo.remove(db=db, id=todo_id)
return Response(status_code=status.HTTP_204_NO_CONTENT)