
- Implement Todo CRUD API endpoints - Set up SQLite database with SQLAlchemy - Create Todo model and schemas - Configure Alembic migrations - Add comprehensive documentation 🤖 Generated with and Co-Authored by [BackendIM](https://backend.im)
101 lines
2.5 KiB
Python
101 lines
2.5 KiB
Python
from typing import Any, List, Optional
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, Path
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app import models, schemas
|
|
from app.db.deps import get_db
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("/", response_model=List[schemas.Todo])
|
|
def read_todos(
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
completed: Optional[bool] = None,
|
|
db: Session = Depends(get_db),
|
|
) -> Any:
|
|
"""
|
|
Retrieve all todos with optional filtering by completed status
|
|
"""
|
|
# Filter todos by completed status if provided
|
|
if completed is not None:
|
|
todos = db.query(models.Todo).filter(models.Todo.completed == completed).offset(skip).limit(limit).all()
|
|
else:
|
|
todos = db.query(models.Todo).offset(skip).limit(limit).all()
|
|
return todos
|
|
|
|
|
|
@router.post("/", response_model=schemas.Todo, status_code=201)
|
|
def create_todo(
|
|
todo_in: schemas.TodoCreate,
|
|
db: Session = Depends(get_db),
|
|
) -> Any:
|
|
"""
|
|
Create new todo
|
|
"""
|
|
todo = models.Todo(
|
|
title=todo_in.title,
|
|
description=todo_in.description,
|
|
completed=todo_in.completed,
|
|
)
|
|
db.add(todo)
|
|
db.commit()
|
|
db.refresh(todo)
|
|
return todo
|
|
|
|
|
|
@router.get("/{todo_id}", response_model=schemas.Todo)
|
|
def read_todo(
|
|
todo_id: int = Path(..., gt=0),
|
|
db: Session = Depends(get_db),
|
|
) -> Any:
|
|
"""
|
|
Get a specific todo by id
|
|
"""
|
|
todo = db.query(models.Todo).filter(models.Todo.id == todo_id).first()
|
|
if not todo:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
return todo
|
|
|
|
|
|
@router.put("/{todo_id}", response_model=schemas.Todo)
|
|
def update_todo(
|
|
*,
|
|
todo_id: int = Path(..., gt=0),
|
|
todo_in: schemas.TodoUpdate,
|
|
db: Session = Depends(get_db),
|
|
) -> Any:
|
|
"""
|
|
Update a todo
|
|
"""
|
|
todo = db.query(models.Todo).filter(models.Todo.id == todo_id).first()
|
|
if not todo:
|
|
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(todo, field, value)
|
|
|
|
db.add(todo)
|
|
db.commit()
|
|
db.refresh(todo)
|
|
return todo
|
|
|
|
|
|
@router.delete("/{todo_id}", response_model=schemas.Todo)
|
|
def delete_todo(
|
|
todo_id: int = Path(..., gt=0),
|
|
db: Session = Depends(get_db),
|
|
) -> Any:
|
|
"""
|
|
Delete a todo
|
|
"""
|
|
todo = db.query(models.Todo).filter(models.Todo.id == todo_id).first()
|
|
if not todo:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
|
|
db.delete(todo)
|
|
db.commit()
|
|
return todo |