2025-05-26 17:55:11 +00:00

120 lines
3.2 KiB
Python

from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.crud import todo as todo_crud
from app.db.session import get_db
from app.schemas.todo import TodoCreate, TodoResponse, TodoUpdate
router = APIRouter()
@router.get("", response_model=List[TodoResponse])
def get_todos(
skip: int = 0,
limit: int = 100,
completed: Optional[bool] = None,
db: Session = Depends(get_db),
):
"""
Retrieve a list of todo items with optional filtering and pagination.
Args:
skip: Number of records to skip (for pagination)
limit: Maximum number of records to return
completed: Filter by completion status if provided
db: Database session
Returns:
List of todo items
"""
todos = todo_crud.get_todos(
db=db, skip=skip, limit=limit, completed=completed
)
return todos
@router.post("", response_model=TodoResponse, status_code=status.HTTP_201_CREATED)
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
"""
Create a new todo item.
Args:
todo: Todo data for creation
db: Database session
Returns:
The created todo item
"""
return todo_crud.create_todo(db=db, todo=todo)
@router.get("/{todo_id}", response_model=TodoResponse)
def get_todo(todo_id: int, db: Session = Depends(get_db)):
"""
Retrieve a specific todo item by ID.
Args:
todo_id: ID of the todo to retrieve
db: Database session
Returns:
The requested todo item
Raises:
HTTPException: If todo item is not found
"""
db_todo = todo_crud.get_todo(db=db, todo_id=todo_id)
if db_todo is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Todo with ID {todo_id} not found",
)
return db_todo
@router.patch("/{todo_id}", response_model=TodoResponse)
def update_todo(todo_id: int, todo_update: TodoUpdate, db: Session = Depends(get_db)):
"""
Update a specific todo item.
Args:
todo_id: ID of the todo to update
todo_update: Todo data for update
db: Database session
Returns:
The updated todo item
Raises:
HTTPException: If todo item is not found
"""
db_todo = todo_crud.update_todo(db=db, todo_id=todo_id, todo_update=todo_update)
if db_todo is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Todo with ID {todo_id} not found",
)
return db_todo
@router.delete("/{todo_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
"""
Delete a specific todo item.
Args:
todo_id: ID of the todo to delete
db: Database session
Raises:
HTTPException: If todo item is not found
"""
success = todo_crud.delete_todo(db=db, todo_id=todo_id)
if not success:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Todo with ID {todo_id} not found",
)
return None