Skip to content

Commit bbac597

Browse files
committed
Todo path operations file
1 parent b19ae0c commit bbac597

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

ch02/todos/todo.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
from fastapi import APIRouter, Path
2+
from model import Todo, TodoItem
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")
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+
return {
32+
"message": "Todo with supplied ID doesn't exist."
33+
}
34+
35+
36+
@todo_router.put("/todo/{todo_id}")
37+
async def update_todo(todo_data: TodoItem, todo_id: int = Path(..., title="The ID of the todo to be updated.")):
38+
for todo in todo_list:
39+
if todo.id == todo_id:
40+
todo.item = todo_data.item
41+
return {
42+
"message": "Todo updated successfully."
43+
}
44+
return {
45+
"message": "Todo with supplied ID doesn't exist."
46+
}
47+
48+
49+
@todo_router.delete("/todo/{todo_id}")
50+
async def delete_single_todo(todo_id: int):
51+
for index in range(len(todo_list)):
52+
todo = todo_list[index]
53+
if todo.id == todo_id:
54+
todo_list.pop(index)
55+
return {
56+
"message": "Todo deleted successfully."
57+
}
58+
return {
59+
"message": "Todo with supplied ID doesn't exist."
60+
}
61+
62+
63+
@todo_router.delete("/todo")
64+
async def delete_all_todo():
65+
todo_list.clear()
66+
return {
67+
"message": "Todos deleted successfully."
68+
}

0 commit comments

Comments
 (0)