
- Add Priority enum (low, medium, high) to Todo model with default medium - Create migration to add priority field to existing todos table - Enhance pagination with proper metadata (page, total, has_next, has_prev) - Add search functionality across title and description fields - Add filtering by completion status and priority level - Update API endpoints with query parameters for filtering and search - Add TodoListResponse schema for structured pagination response - Format code with Ruff
72 lines
2.3 KiB
Python
72 lines
2.3 KiB
Python
from typing import Optional
|
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
|
from sqlalchemy.orm import Session
|
|
import math
|
|
|
|
from app.crud import todo as todo_crud
|
|
from app.db.session import get_db
|
|
from app.models.todo import Priority
|
|
from app.schemas.todo import Todo, TodoCreate, TodoUpdate, TodoListResponse
|
|
|
|
router = APIRouter(prefix="/todos", tags=["todos"])
|
|
|
|
|
|
@router.get("/", response_model=TodoListResponse)
|
|
def read_todos(
|
|
page: int = Query(1, ge=1, description="Page number"),
|
|
per_page: int = Query(10, ge=1, le=100, description="Items per page"),
|
|
completed: Optional[bool] = Query(None, description="Filter by completion status"),
|
|
priority: Optional[Priority] = Query(None, description="Filter by priority"),
|
|
search: Optional[str] = Query(None, description="Search in title and description"),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
skip = (page - 1) * per_page
|
|
todos, total = todo_crud.get_todos(
|
|
db,
|
|
skip=skip,
|
|
limit=per_page,
|
|
completed=completed,
|
|
priority=priority,
|
|
search=search,
|
|
)
|
|
|
|
total_pages = math.ceil(total / per_page)
|
|
|
|
return TodoListResponse(
|
|
items=todos,
|
|
total=total,
|
|
page=page,
|
|
per_page=per_page,
|
|
has_next=page < total_pages,
|
|
has_prev=page > 1,
|
|
)
|
|
|
|
|
|
@router.post("/", response_model=Todo)
|
|
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
|
|
return todo_crud.create_todo(db=db, todo=todo)
|
|
|
|
|
|
@router.get("/{todo_id}", response_model=Todo)
|
|
def read_todo(todo_id: int, db: Session = Depends(get_db)):
|
|
db_todo = todo_crud.get_todo(db, todo_id=todo_id)
|
|
if db_todo is None:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
return db_todo
|
|
|
|
|
|
@router.put("/{todo_id}", response_model=Todo)
|
|
def update_todo(todo_id: int, todo_update: TodoUpdate, db: Session = Depends(get_db)):
|
|
db_todo = todo_crud.update_todo(db, todo_id=todo_id, todo_update=todo_update)
|
|
if db_todo is None:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
return db_todo
|
|
|
|
|
|
@router.delete("/{todo_id}")
|
|
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
|
|
success = todo_crud.delete_todo(db, todo_id=todo_id)
|
|
if not success:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
return {"message": "Todo deleted successfully"}
|