114 lines
2.7 KiB
Python
114 lines
2.7 KiB
Python
from typing import List
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Path, Query, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.crud import todo as todo_crud
|
|
from app.db.session import get_db
|
|
from app.schemas.todo import TodoCreate, TodoResponse, TodoUpdate
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("/", response_model=List[TodoResponse])
|
|
async def get_todos(
|
|
skip: int = Query(0, ge=0),
|
|
limit: int = Query(100, ge=1, le=100),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""
|
|
Get all todos.
|
|
|
|
Args:
|
|
skip: Number of records to skip.
|
|
limit: Maximum number of records to return.
|
|
db: Database session.
|
|
|
|
Returns:
|
|
List of todos.
|
|
"""
|
|
todos = todo_crud.get_todos(db, skip=skip, limit=limit)
|
|
return todos
|
|
|
|
|
|
@router.post("/", response_model=TodoResponse, status_code=status.HTTP_201_CREATED)
|
|
async def create_todo(
|
|
todo: TodoCreate,
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""
|
|
Create a new todo.
|
|
|
|
Args:
|
|
todo: Todo to create.
|
|
db: Database session.
|
|
|
|
Returns:
|
|
Created todo.
|
|
"""
|
|
return todo_crud.create_todo(db=db, todo=todo)
|
|
|
|
|
|
@router.get("/{todo_id}", response_model=TodoResponse)
|
|
async def get_todo(
|
|
todo_id: int = Path(..., gt=0),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""
|
|
Get a specific todo by ID.
|
|
|
|
Args:
|
|
todo_id: ID of the todo to get.
|
|
db: Database session.
|
|
|
|
Returns:
|
|
Todo with the specified ID.
|
|
"""
|
|
db_todo = todo_crud.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=TodoResponse)
|
|
async def update_todo(
|
|
todo: TodoUpdate,
|
|
todo_id: int = Path(..., gt=0),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""
|
|
Update a todo.
|
|
|
|
Args:
|
|
todo: Todo data to update.
|
|
todo_id: ID of the todo to update.
|
|
db: Database session.
|
|
|
|
Returns:
|
|
Updated todo.
|
|
"""
|
|
db_todo = todo_crud.update_todo(db, todo_id=todo_id, todo=todo)
|
|
if db_todo is None:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
return db_todo
|
|
|
|
|
|
@router.delete("/{todo_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
|
async def delete_todo(
|
|
todo_id: int = Path(..., gt=0),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""
|
|
Delete a todo.
|
|
|
|
Args:
|
|
todo_id: ID of the todo to delete.
|
|
db: Database session.
|
|
|
|
Returns:
|
|
204 No Content on success.
|
|
"""
|
|
result = todo_crud.delete_todo(db, todo_id=todo_id)
|
|
if not result:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
return None |