2025-05-16 10:29:16 +00:00

103 lines
2.6 KiB
Python

from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app import crud
from app.db.session import get_db
from app.schemas.todo import Todo, TodoCreate, TodoUpdate
router = APIRouter()
@router.get("/", response_model=List[Todo])
def read_todos(
skip: int = 0,
limit: int = 100,
completed: Optional[bool] = None,
db: Session = Depends(get_db),
):
"""
Retrieve todos.
- **skip**: Number of records to skip for pagination
- **limit**: Maximum number of records to retrieve
- **completed**: Filter todos by completion status (optional)
"""
todos = crud.crud_todo.get_todos(db, skip=skip, limit=limit, completed=completed)
return todos
@router.post("/", response_model=Todo, status_code=status.HTTP_201_CREATED)
def create_todo(
todo_in: TodoCreate,
db: Session = Depends(get_db),
):
"""
Create new todo.
- **title**: Title for the todo (required)
- **description**: Detailed description (optional)
- **completed**: Completion status (defaults to False)
"""
return crud.crud_todo.create_todo(db=db, todo=todo_in)
@router.get("/{todo_id}", response_model=Todo)
def read_todo(
todo_id: int,
db: Session = Depends(get_db),
):
"""
Get specific todo by ID.
- **todo_id**: The ID of the todo to retrieve
"""
db_todo = crud.crud_todo.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_in: TodoUpdate,
db: Session = Depends(get_db),
):
"""
Update a todo.
- **todo_id**: The ID of the todo to update
- **title**: New title (optional)
- **description**: New description (optional)
- **completed**: New completion status (optional)
"""
db_todo = crud.crud_todo.get_todo(db, todo_id=todo_id)
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
db_todo = crud.crud_todo.update_todo(db=db, todo_id=todo_id, todo_in=todo_in)
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 todo.
- **todo_id**: The ID of the todo to delete
"""
db_todo = crud.crud_todo.get_todo(db, todo_id=todo_id)
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
crud.crud_todo.delete_todo(db=db, todo_id=todo_id)
return None