
- Set up project structure and FastAPI application - Create database models with SQLAlchemy - Set up Alembic for database migrations - Create API endpoints for todo CRUD operations - Add health check endpoint - Add unit tests for API endpoints - Configure Ruff for linting and formatting
77 lines
2.3 KiB
Python
77 lines
2.3 KiB
Python
from typing import List
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.db.session import get_db
|
|
from app.models.todo import Todo
|
|
from app.schemas.todo import TodoCreate, TodoResponse, TodoUpdate
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.post("", response_model=TodoResponse, status_code=status.HTTP_201_CREATED)
|
|
def create_todo(todo_in: TodoCreate, db: Session = Depends(get_db)) -> TodoResponse:
|
|
"""Create a new todo item."""
|
|
db_todo = Todo(
|
|
title=todo_in.title,
|
|
description=todo_in.description,
|
|
completed=todo_in.completed,
|
|
)
|
|
db.add(db_todo)
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
|
|
@router.get("", response_model=List[TodoResponse])
|
|
def read_todos(
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
db: Session = Depends(get_db),
|
|
) -> List[TodoResponse]:
|
|
"""Read all todo items with pagination."""
|
|
todos = db.query(Todo).offset(skip).limit(limit).all()
|
|
return todos
|
|
|
|
|
|
@router.get("/{todo_id}", response_model=TodoResponse)
|
|
def read_todo(todo_id: int, db: Session = Depends(get_db)) -> TodoResponse:
|
|
"""Read 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=status.HTTP_404_NOT_FOUND, detail="Todo not found")
|
|
return db_todo
|
|
|
|
|
|
@router.put("/{todo_id}", response_model=TodoResponse)
|
|
def update_todo(
|
|
todo_id: int,
|
|
todo_in: TodoUpdate,
|
|
db: Session = Depends(get_db),
|
|
) -> TodoResponse:
|
|
"""Update a todo item."""
|
|
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
|
if db_todo is None:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Todo not found")
|
|
|
|
update_data = todo_in.model_dump(exclude_unset=True)
|
|
for field, value in update_data.items():
|
|
setattr(db_todo, field, value)
|
|
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
|
|
@router.delete("/{todo_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
|
def delete_todo(todo_id: int, db: Session = Depends(get_db)) -> None:
|
|
"""Delete a todo item."""
|
|
db_todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
|
if db_todo is None:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Todo not found")
|
|
|
|
db.delete(db_todo)
|
|
db.commit()
|
|
return None
|