2025-05-22 19:30:08 +00:00

92 lines
2.2 KiB
Python

from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app import crud, schemas
from app.api import deps
router = APIRouter()
@router.get("/", response_model=List[schemas.todo.Todo])
def read_todos(
skip: int = 0,
limit: int = 100,
db: Session = Depends(deps.get_db_session),
) -> List[schemas.todo.Todo]:
"""
Retrieve todos.
"""
todos = crud.todo.get_todos(db, skip=skip, limit=limit)
return todos
@router.post("/", response_model=schemas.todo.Todo, status_code=status.HTTP_201_CREATED)
def create_todo(
*,
todo_in: schemas.todo.TodoCreate,
db: Session = Depends(deps.get_db_session),
) -> schemas.todo.Todo:
"""
Create new todo.
"""
todo = crud.todo.create_todo(db=db, todo=todo_in)
return todo
@router.get("/{todo_id}", response_model=schemas.todo.Todo)
def read_todo(
*,
todo_id: int,
db: Session = Depends(deps.get_db_session),
) -> schemas.todo.Todo:
"""
Get todo by ID.
"""
todo = crud.todo.get_todo(db=db, todo_id=todo_id)
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Todo not found",
)
return todo
@router.put("/{todo_id}", response_model=schemas.todo.Todo)
def update_todo(
*,
todo_id: int,
todo_in: schemas.todo.TodoUpdate,
db: Session = Depends(deps.get_db_session),
) -> schemas.todo.Todo:
"""
Update a todo.
"""
todo = crud.todo.get_todo(db=db, todo_id=todo_id)
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Todo not found",
)
todo = crud.todo.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(deps.get_db_session),
) -> None:
"""
Delete a todo.
"""
todo = crud.todo.get_todo(db=db, todo_id=todo_id)
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Todo not found",
)
crud.todo.delete_todo(db=db, todo_id=todo_id)
return None