-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
82 lines (64 loc) · 2.55 KB
/
Copy pathmain.py
File metadata and controls
82 lines (64 loc) · 2.55 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
"""
Task Manager REST API
=======================
A small FastAPI service for creating, reading, updating, and deleting tasks,
backed by SQLite via SQLAlchemy.
Run locally with:
uvicorn main:app --reload
Then open http://127.0.0.1:8000/docs for interactive API docs.
"""
from typing import List, Optional
from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.orm import Session
from database import Base, engine, get_db
from models import Task, TaskCreate, TaskOut, TaskUpdate
Base.metadata.create_all(bind=engine)
app = FastAPI(
title="Task Manager API",
description="A simple REST API for managing personal tasks.",
version="1.0.0",
)
@app.get("/", tags=["meta"])
def root():
return {"message": "Task Manager API. See /docs for interactive API docs."}
@app.post("/tasks", response_model=TaskOut, status_code=201, tags=["tasks"])
def create_task(task: TaskCreate, db: Session = Depends(get_db)):
db_task = Task(title=task.title, description=task.description, status=task.status.value)
db.add(db_task)
db.commit()
db.refresh(db_task)
return db_task
@app.get("/tasks", response_model=List[TaskOut], tags=["tasks"])
def list_tasks(status: Optional[str] = None, db: Session = Depends(get_db)):
query = db.query(Task)
if status:
query = query.filter(Task.status == status)
return query.order_by(Task.created_at.desc()).all()
@app.get("/tasks/{task_id}", response_model=TaskOut, tags=["tasks"])
def get_task(task_id: int, db: Session = Depends(get_db)):
task = db.query(Task).filter(Task.id == task_id).first()
if not task:
raise HTTPException(status_code=404, detail="Task not found")
return task
@app.patch("/tasks/{task_id}", response_model=TaskOut, tags=["tasks"])
def update_task(task_id: int, update: TaskUpdate, db: Session = Depends(get_db)):
task = db.query(Task).filter(Task.id == task_id).first()
if not task:
raise HTTPException(status_code=404, detail="Task not found")
if update.title is not None:
task.title = update.title
if update.description is not None:
task.description = update.description
if update.status is not None:
task.status = update.status.value
db.commit()
db.refresh(task)
return task
@app.delete("/tasks/{task_id}", status_code=204, tags=["tasks"])
def delete_task(task_id: int, db: Session = Depends(get_db)):
task = db.query(Task).filter(Task.id == task_id).first()
if not task:
raise HTTPException(status_code=404, detail="Task not found")
db.delete(task)
db.commit()
return None