2025-05-16 04:32:55 +00:00

72 lines
2.3 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from app.db.database import get_db
from app.db.models import Todo
from app.schemas.todo import TodoCreate, TodoResponse, TodoUpdate
# Create routers
todo_router = APIRouter()
health_router = APIRouter()
@health_router.get("/health")
def health_check():
"""Health check endpoint"""
return {"status": "healthy"}
@todo_router.post("/todos/", response_model=TodoResponse, status_code=status.HTTP_201_CREATED)
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
"""Create a new todo item"""
db_todo = Todo(title=todo.title, description=todo.description, completed=todo.completed)
db.add(db_todo)
db.commit()
db.refresh(db_todo)
return db_todo
@todo_router.get("/todos/", response_model=List[TodoResponse])
def read_todos(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
"""Get all todo items"""
todos = db.query(Todo).offset(skip).limit(limit).all()
return todos
@todo_router.get("/todos/{todo_id}", response_model=TodoResponse)
def read_todo(todo_id: int, db: Session = Depends(get_db)):
"""Get a specific todo item by ID"""
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
return db_todo
@todo_router.put("/todos/{todo_id}", response_model=TodoResponse)
def update_todo(todo_id: int, todo: TodoUpdate, db: Session = Depends(get_db)):
"""Update a todo item"""
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
# Update todo fields if they exist in the request
update_data = todo.dict(exclude_unset=True)
for key, value in update_data.items():
setattr(db_todo, key, value)
db.commit()
db.refresh(db_todo)
return db_todo
@todo_router.delete("/todos/{todo_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
"""Delete a todo item"""
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
db.delete(db_todo)
db.commit()
return None