-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
147 lines (122 loc) · 4.13 KB
/
Copy pathmain.py
File metadata and controls
147 lines (122 loc) · 4.13 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
from fastapi import FastAPI, HTTPException, Depends
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from datetime import datetime
from typing import List
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from database import init_db, get_session
from models import TaskDB, TaskCreate, TaskUpdate, TaskResponse
# Create the FastAPI app with startup/shutdown events
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup: Create database tables
print("📦 Initializing database...")
await init_db()
print("✅ Database initialized!")
yield
# Shutdown: Cleanup happens here if needed
print("👋 Shutting down...")
app = FastAPI(
title="Task Manager API",
description="A simple CRUD API for managing tasks",
version="1.0.0",
lifespan=lifespan
)
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3001"],
allow_methods=["*"],
allow_headers=["*"],
)
# ===== ENDPOINTS =====
@app.get("/")
async def read_root():
"""Health check endpoint"""
return {"message": "Task Manager API is running! 🚀"}
# ===== CREATE: POST /tasks =====
@app.post("/tasks", response_model=TaskResponse)
async def create_task(task: TaskCreate, session: AsyncSession = Depends(get_session)):
"""
Create a new task.
Example request body:
{
"title": "Buy groceries",
"description": "Milk, eggs, bread",
"status": "pending"
}
"""
# Create a new TaskDB object
db_task = TaskDB(
title=task.title,
description=task.description,
status=task.status
)
# Add to session and commit
session.add(db_task)
await session.commit()
await session.refresh(db_task)
return db_task
# ===== READ: GET /tasks =====
@app.get("/tasks", response_model=List[TaskResponse])
async def get_all_tasks(session: AsyncSession = Depends(get_session)):
"""
Get all tasks.
Returns a list of all tasks in the database.
"""
result = await session.execute(select(TaskDB))
tasks = result.scalars().all()
return tasks
# ===== READ: GET /tasks/{task_id} =====
@app.get("/tasks/{task_id}", response_model=TaskResponse)
async def get_task(task_id: int, session: AsyncSession = Depends(get_session)):
"""
Get a specific task by ID.
"""
result = await session.execute(select(TaskDB).where(TaskDB.id == task_id))
task = result.scalar_one_or_none()
if not task:
raise HTTPException(status_code=404, detail=f"Task {task_id} not found")
return task
# ===== UPDATE: PATCH /tasks/{task_id} =====
@app.patch("/tasks/{task_id}", response_model=TaskResponse)
async def update_task(task_id: int, task_update: TaskUpdate, session: AsyncSession = Depends(get_session)):
"""
Update a task. Only provide the fields you want to change.
Example request body:
{
"status": "completed"
}
"""
# Fetch the task
result = await session.execute(select(TaskDB).where(TaskDB.id == task_id))
db_task = result.scalar_one_or_none()
if not db_task:
raise HTTPException(status_code=404, detail=f"Task {task_id} not found")
# Update only the fields that were provided
update_data = task_update.model_dump(exclude_unset=True)
for field, value in update_data.items():
setattr(db_task, field, value)
# Save changes
session.add(db_task)
await session.commit()
await session.refresh(db_task)
return db_task
# ===== DELETE: DELETE /tasks/{task_id} =====
@app.delete("/tasks/{task_id}")
async def delete_task(task_id: int, session: AsyncSession = Depends(get_session)):
"""
Delete a task by ID.
"""
# Fetch the task
result = await session.execute(select(TaskDB).where(TaskDB.id == task_id))
db_task = result.scalar_one_or_none()
if not db_task:
raise HTTPException(status_code=404, detail=f"Task {task_id} not found")
# Delete it
await session.delete(db_task)
await session.commit()
return {"message": f"Task {task_id} deleted successfully"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)