fastapi-svelte-template/backend/todo/routes/todos.py

72 lines
2.5 KiB
Python

"""This module contains endpoints for operations related to users."""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from todo.database.engine import get_db
from todo.schemas import todos as todoschema
from todo.crud import todos as todocrud
from todo.utils.exceptions import NotFoundException, InvalidFilterParameterException
from todo.utils.exceptions import create_exception_dict as fmt
router = APIRouter(
prefix="/todo",
tags=["todo-items"]
)
tag_metadata = {
"name": "todo-items",
"description": "Operations related to todo items."
}
@router.post("/user/{user_id}", response_model=todoschema.TodoItem)
def create_todo(todo: todoschema.TodoItemCreate, user_id: int, db: Session = Depends(get_db)):
try:
return todocrud.create_todo(db=db, todo=todo, user_id=user_id)
except NotFoundException as e:
raise HTTPException(404, fmt(str(e)))
@router.get("/{todo_id}", response_model=todoschema.TodoItem)
def read_todo(todo_id: int, db: Session = Depends(get_db)):
try:
return todocrud.read_todo(db=db, todo_id=todo_id)
except NotFoundException as e:
raise HTTPException(404, fmt(str(e)))
@router.get("/user/{user_id}", response_model=list[todoschema.TodoItem])
def read_todos(user_id: int, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
try:
return todocrud.read_todos_for_user(db=db, user_id=user_id, skip=skip, limit=limit)
except InvalidFilterParameterException as e:
raise HTTPException(400, fmt(str(e)))
except NotFoundException as e:
raise HTTPException(404, fmt(str(e)))
@router.get("/user/{user_id}/total", response_model=dict[str, int])
def read_todos_count(user_id: int, db: Session = Depends(get_db)):
try:
return {"total": todocrud.read_todos_count_for_user(db=db, user_id=user_id)}
except NotFoundException as e:
raise HTTPException(404, fmt(str(e)))
@router.patch("/{todo_id}", response_model=todoschema.TodoItem)
def update_todo(todo_id: int, todo: todoschema.TodoItemUpdate, db: Session = Depends(get_db)):
try:
return todocrud.update_todo(db=db, todo=todo, todo_id=todo_id)
except NotFoundException as e:
raise HTTPException(404, fmt(str(e)))
@router.delete("/{todo_id}", response_model=todoschema.TodoItem)
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
try:
return todocrud.delete_todo(db=db, todo_id=todo_id)
except NotFoundException as e:
raise HTTPException(404, fmt(str(e)))