72 lines
1.9 KiB
Python
72 lines
1.9 KiB
Python
from typing import Any, List, Optional
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app import crud, schemas
|
|
from app.db.session import get_db
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("/", response_model=List[schemas.Todo])
|
|
def read_todos(
|
|
db: Session = Depends(get_db),
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
is_completed: Optional[bool] = None,
|
|
) -> Any:
|
|
"""Retrieve todos."""
|
|
if is_completed is not None:
|
|
todos = crud.todo.get_multi_by_completed(
|
|
db, is_completed=is_completed, skip=skip, limit=limit
|
|
)
|
|
else:
|
|
todos = crud.todo.get_multi(db, skip=skip, limit=limit)
|
|
return todos
|
|
|
|
|
|
@router.post("/", response_model=schemas.Todo)
|
|
def create_todo(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
todo_in: schemas.TodoCreate,
|
|
) -> Any:
|
|
"""Create new todo."""
|
|
todo = crud.todo.create(db=db, obj_in=todo_in)
|
|
return todo
|
|
|
|
|
|
@router.get("/{id}", response_model=schemas.Todo)
|
|
def read_todo(*, db: Session = Depends(get_db), id: int) -> Any:
|
|
"""Get todo by ID."""
|
|
todo = crud.todo.get(db=db, id=id)
|
|
if not todo:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
return todo
|
|
|
|
|
|
@router.put("/{id}", response_model=schemas.Todo)
|
|
def update_todo(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
id: int,
|
|
todo_in: schemas.TodoUpdate,
|
|
) -> Any:
|
|
"""Update a todo."""
|
|
todo = crud.todo.get(db=db, id=id)
|
|
if not todo:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
todo = crud.todo.update(db=db, db_obj=todo, obj_in=todo_in)
|
|
return todo
|
|
|
|
|
|
@router.delete("/{id}", response_model=schemas.Todo)
|
|
def delete_todo(*, db: Session = Depends(get_db), id: int) -> Any:
|
|
"""Delete a todo."""
|
|
todo = crud.todo.get(db=db, id=id)
|
|
if not todo:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
todo = crud.todo.remove(db=db, id=id)
|
|
return todo
|