Repository navigation
Expand file tree
/
Copy pathsandbox.py
More file actions
52 lines (44 loc) · 1.36 KB
/
Copy pathsandbox.py
File metadata and controls
52 lines (44 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class Habit(BaseModel):
title: str
completed: bool = False
# Temporary in-memory storage (resets when Uvicorn restarts)
habits: list[dict] = []
next_id = 1
@app.post("/habits", status_code=201)
def create_habit(habit: Habit):
global next_id
new_habit = {
"id": next_id,
"title": habit.title,
"completed": habit.completed,
}
habits.append(new_habit)
next_id += 1
return new_habit
@app.get("/habits")
def get_habits():
return habits
@app.get("/habits/{habit_id}")
def get_habit(habit_id: int):
for h in habits:
if h["id"] == habit_id:
return h
raise HTTPException(status_code=404, detail="Habit not found")
@app.put("/habits/{habit_id}")
def update_habit(habit_id: int, habit: Habit):
for h in habits:
if h["id"] == habit_id:
h["title"] = habit.title
h["completed"] = habit.completed
return h
raise HTTPException(status_code=404, detail="Habit not found")
@app.delete("/habits/{habit_id}")
def delete_habit(habit_id: int):
for i, h in enumerate(habits):
if h["id"] == habit_id:
deleted = habits.pop(i)
return {"message": "Habit deleted", "habit": deleted}
raise HTTPException(status_code=404, detail="Habit not found")