
- Setup project structure with FastAPI, SQLAlchemy, and SQLite - Create Todo model and database migrations - Implement CRUD API endpoints - Add error handling and validation - Update README with documentation and examples generated with BackendIM... (backend.im)
81 lines
2.4 KiB
Python
81 lines
2.4 KiB
Python
from typing import List, Optional
|
|
from fastapi import APIRouter, Depends, status, Query
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.exceptions import TodoNotFoundException
|
|
from app.db.session import get_db
|
|
from app.models.todo import Todo as TodoModel
|
|
from app.schemas.todo import Todo, TodoCreate, TodoUpdate
|
|
|
|
router = APIRouter(prefix="/todos", tags=["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)
|
|
):
|
|
"""
|
|
Retrieve all todos with optional filtering by completion status.
|
|
"""
|
|
query = db.query(TodoModel)
|
|
|
|
# Filter by completion status if provided
|
|
if completed is not None:
|
|
query = query.filter(TodoModel.completed == completed)
|
|
|
|
todos = query.offset(skip).limit(limit).all()
|
|
return todos
|
|
|
|
@router.post("/", response_model=Todo, status_code=status.HTTP_201_CREATED)
|
|
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
|
|
"""
|
|
Create a new todo item.
|
|
"""
|
|
db_todo = TodoModel(**todo.dict())
|
|
db.add(db_todo)
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
@router.get("/{todo_id}", response_model=Todo)
|
|
def read_todo(todo_id: int, db: Session = Depends(get_db)):
|
|
"""
|
|
Get a specific todo by ID.
|
|
"""
|
|
db_todo = db.query(TodoModel).filter(TodoModel.id == todo_id).first()
|
|
if db_todo is None:
|
|
raise TodoNotFoundException(todo_id=todo_id)
|
|
return db_todo
|
|
|
|
@router.put("/{todo_id}", response_model=Todo)
|
|
def update_todo(todo_id: int, todo: 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 TodoNotFoundException(todo_id=todo_id)
|
|
|
|
# Update only the fields that are provided
|
|
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
|
|
|
|
@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 TodoNotFoundException(todo_id=todo_id)
|
|
|
|
db.delete(db_todo)
|
|
db.commit()
|
|
return None |