102 lines
2.8 KiB
Python
102 lines
2.8 KiB
Python
from typing import List, Optional
|
|
from fastapi import APIRouter, Depends, HTTPException, status, Query
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.db.base import get_db
|
|
from app.models.todo import Todo
|
|
from app.schemas.todo import TodoCreate, TodoUpdate, TodoResponse
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.post("/todos", response_model=TodoResponse, status_code=status.HTTP_201_CREATED)
|
|
def create_todo(
|
|
todo: TodoCreate,
|
|
db: Session = Depends(get_db)
|
|
) -> Todo:
|
|
"""Create a new todo item."""
|
|
db_todo = Todo(
|
|
title=todo.title,
|
|
description=todo.description,
|
|
completed=todo.completed
|
|
)
|
|
db.add(db_todo)
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
|
|
@router.get("/todos", response_model=List[TodoResponse])
|
|
def read_todos(
|
|
skip: int = Query(0, ge=0),
|
|
limit: int = Query(100, ge=1, le=100),
|
|
completed: Optional[bool] = None,
|
|
db: Session = Depends(get_db)
|
|
) -> List[Todo]:
|
|
"""Get all todos with optional filtering and pagination."""
|
|
query = db.query(Todo)
|
|
|
|
# Apply filtering if completed status is provided
|
|
if completed is not None:
|
|
query = query.filter(Todo.completed == completed)
|
|
|
|
# Apply pagination
|
|
todos = query.offset(skip).limit(limit).all()
|
|
return todos
|
|
|
|
|
|
@router.get("/todos/{todo_id}", response_model=TodoResponse)
|
|
def read_todo(
|
|
todo_id: int,
|
|
db: Session = Depends(get_db)
|
|
) -> Todo:
|
|
"""Get a specific todo by id."""
|
|
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
|
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.put("/todos/{todo_id}", response_model=TodoResponse)
|
|
def update_todo(
|
|
todo_id: int,
|
|
todo: TodoUpdate,
|
|
db: Session = Depends(get_db)
|
|
) -> Todo:
|
|
"""Update a todo item."""
|
|
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
|
if db_todo is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Todo with id {todo_id} not found"
|
|
)
|
|
|
|
# Update fields if provided
|
|
update_data = todo.model_dump(exclude_unset=True)
|
|
for key, value in update_data.items():
|
|
setattr(db_todo, key, value)
|
|
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
|
|
@router.delete("/todos/{todo_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
|
def delete_todo(
|
|
todo_id: int,
|
|
db: Session = Depends(get_db)
|
|
) -> None:
|
|
"""Delete a todo item."""
|
|
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
|
if db_todo is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Todo with id {todo_id} not found"
|
|
)
|
|
|
|
db.delete(db_todo)
|
|
db.commit()
|
|
return None |