|
| 1 | +from fastapi import APIRouter, Path, HTTPException, status |
| 2 | +from model import Todo, TodoItem, TodoItems |
| 3 | + |
| 4 | +todo_router = APIRouter() |
| 5 | + |
| 6 | +todo_list = [] |
| 7 | + |
| 8 | + |
| 9 | +@todo_router.post("/todo") |
| 10 | +async def add_todo(todo: Todo): |
| 11 | + todo_list.append(todo) |
| 12 | + return { |
| 13 | + "message": "Todo added successfully." |
| 14 | + } |
| 15 | + |
| 16 | + |
| 17 | +@todo_router.get("/todo", response_model=TodoItems) |
| 18 | +async def retrieve_todo(): |
| 19 | + return { |
| 20 | + "todos": todo_list |
| 21 | + } |
| 22 | + |
| 23 | + |
| 24 | +@todo_router.get("/todo/{todo_id}") |
| 25 | +async def get_single_todo(todo_id: int = Path(..., title="The ID of the todo to retrieve.")): |
| 26 | + for todo in todo_list: |
| 27 | + if todo.id == todo_id: |
| 28 | + return { |
| 29 | + "todo": todo |
| 30 | + } |
| 31 | + raise HTTPException( |
| 32 | + status_code=status.HTTP_404_NOT_FOUND, |
| 33 | + detail="Todo with supplied ID doesn't exist", |
| 34 | + ) |
| 35 | + |
| 36 | + |
| 37 | +@todo_router.put("/todo/{todo_id}") |
| 38 | +async def update_todo(todo_data: TodoItem, todo_id: int = Path(..., title="The ID of the todo to be updated.")): |
| 39 | + for todo in todo_list: |
| 40 | + if todo.id == todo_id: |
| 41 | + todo.item = todo_data.item |
| 42 | + return { |
| 43 | + "message": "Todo updated successfully." |
| 44 | + } |
| 45 | + |
| 46 | + raise HTTPException( |
| 47 | + status_code=status.HTTP_404_NOT_FOUND, |
| 48 | + detail="Todo with supplied ID doesn't exist", |
| 49 | + ) |
| 50 | + |
| 51 | + |
| 52 | +@todo_router.delete("/todo/{todo_id}") |
| 53 | +async def delete_single_todo(todo_id: int): |
| 54 | + for index in range(len(todo_list)): |
| 55 | + todo = todo_list[index] |
| 56 | + if todo.id == todo_id: |
| 57 | + todo_list.pop(index) |
| 58 | + return { |
| 59 | + "message": "Todo deleted successfully." |
| 60 | + } |
| 61 | + raise HTTPException( |
| 62 | + status_code=status.HTTP_404_NOT_FOUND, |
| 63 | + detail="Todo with supplied ID doesn't exist", |
| 64 | + ) |
| 65 | + |
| 66 | + |
| 67 | +@todo_router.delete("/todo") |
| 68 | +async def delete_all_todo(): |
| 69 | + todo_list.clear() |
| 70 | + return { |
| 71 | + "message": "Todos deleted successfully." |
| 72 | + } |
0 commit comments