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

63 lines
2.1 KiB
Python
Raw Normal View History

"""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.exceptions import NotFoundException, InvalidFilterParameterException
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, 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, 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, str(e))
except NotFoundException as e:
raise HTTPException(404, 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, 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, str(e))