
- Set up project structure - Configure SQLite database connection - Create Todo model and schema - Implement CRUD API endpoints for todo items - Add health check endpoint - Update README with documentation generated with BackendIM... (backend.im)
69 lines
2.3 KiB
Python
69 lines
2.3 KiB
Python
from typing import List, Optional
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.db.session import get_db
|
|
from app.models.todo import Todo as TodoModel
|
|
from app.schemas.todo import Todo, TodoCreate, TodoUpdate
|
|
|
|
todos_router = APIRouter(prefix="/todos", tags=["todos"])
|
|
|
|
@todos_router.post("/", response_model=Todo, status_code=status.HTTP_201_CREATED)
|
|
def create_todo(todo_in: TodoCreate, db: Session = Depends(get_db)):
|
|
"""Create a new todo item"""
|
|
db_todo = TodoModel(**todo_in.dict())
|
|
db.add(db_todo)
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
@todos_router.get("/", response_model=List[Todo])
|
|
def read_todos(
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
completed: Optional[bool] = None,
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""Get all todo items with optional filtering"""
|
|
query = db.query(TodoModel)
|
|
|
|
if completed is not None:
|
|
query = query.filter(TodoModel.completed == completed)
|
|
|
|
todos = query.offset(skip).limit(limit).all()
|
|
return todos
|
|
|
|
@todos_router.get("/{todo_id}", response_model=Todo)
|
|
def read_todo(todo_id: int, db: Session = Depends(get_db)):
|
|
"""Get a specific todo item by ID"""
|
|
db_todo = db.query(TodoModel).filter(TodoModel.id == todo_id).first()
|
|
if db_todo is None:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
return db_todo
|
|
|
|
@todos_router.patch("/{todo_id}", response_model=Todo)
|
|
def update_todo(todo_id: int, todo_in: TodoUpdate, db: Session = Depends(get_db)):
|
|
"""Update a todo item"""
|
|
db_todo = db.query(TodoModel).filter(TodoModel.id == todo_id).first()
|
|
if db_todo is None:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
|
|
update_data = todo_in.dict(exclude_unset=True)
|
|
for field, value in update_data.items():
|
|
setattr(db_todo, field, value)
|
|
|
|
db.add(db_todo)
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
@todos_router.delete("/{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(TodoModel).filter(TodoModel.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 |