91 lines
2.2 KiB
Python
91 lines
2.2 KiB
Python
from typing import List, Any
|
|
from fastapi import APIRouter, Depends, status, Response
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app import crud
|
|
from app.api.deps import get_db
|
|
from app.schemas.todo import Todo, TodoCreate, TodoUpdate
|
|
from app.core.exceptions import TodoNotFoundException, BadRequestException
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("/", response_model=List[Todo])
|
|
def read_todos(
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
db: Session = Depends(get_db)
|
|
) -> Any:
|
|
"""
|
|
Retrieve todos.
|
|
"""
|
|
todos = crud.get_todos(db, skip=skip, limit=limit)
|
|
return todos
|
|
|
|
|
|
@router.post("/", response_model=Todo, status_code=status.HTTP_201_CREATED)
|
|
def create_todo(
|
|
*,
|
|
todo_in: TodoCreate,
|
|
db: Session = Depends(get_db)
|
|
) -> Any:
|
|
"""
|
|
Create new todo.
|
|
"""
|
|
todo = crud.create_todo(db=db, todo=todo_in)
|
|
return todo
|
|
|
|
|
|
@router.get("/{todo_id}", response_model=Todo)
|
|
def read_todo(
|
|
*,
|
|
todo_id: int,
|
|
db: Session = Depends(get_db)
|
|
) -> Any:
|
|
"""
|
|
Get todo by ID.
|
|
"""
|
|
todo = crud.get_todo(db=db, todo_id=todo_id)
|
|
if not todo:
|
|
raise TodoNotFoundException(todo_id=todo_id)
|
|
return todo
|
|
|
|
|
|
@router.put("/{todo_id}", response_model=Todo)
|
|
def update_todo(
|
|
*,
|
|
todo_id: int,
|
|
todo_in: TodoUpdate,
|
|
db: Session = Depends(get_db)
|
|
) -> Any:
|
|
"""
|
|
Update a todo.
|
|
"""
|
|
todo = crud.get_todo(db=db, todo_id=todo_id)
|
|
if not todo:
|
|
raise TodoNotFoundException(todo_id=todo_id)
|
|
|
|
# Validate that at least one field is provided for update
|
|
update_data = todo_in.model_dump(exclude_unset=True)
|
|
if not update_data:
|
|
raise BadRequestException(detail="No fields provided for update")
|
|
|
|
todo = crud.update_todo(db=db, todo_id=todo_id, todo=todo_in)
|
|
return 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)
|
|
) -> Any:
|
|
"""
|
|
Delete a todo.
|
|
"""
|
|
todo = crud.get_todo(db=db, todo_id=todo_id)
|
|
if not todo:
|
|
raise TodoNotFoundException(todo_id=todo_id)
|
|
|
|
crud.delete_todo(db=db, todo_id=todo_id)
|
|
return Response(status_code=status.HTTP_204_NO_CONTENT) |