
- Set up project structure with FastAPI application - Create Todo model and related Pydantic schemas - Implement CRUD operations for Todo items - Add health endpoint for application monitoring - Configure database connection with SQLite - Create database migrations with Alembic - Update documentation with setup and usage instructions generated with BackendIM... (backend.im)
91 lines
2.4 KiB
Python
91 lines
2.4 KiB
Python
from typing import List
|
|
from fastapi import APIRouter, Depends, HTTPException, status, Query
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.db.database import get_db
|
|
from app.models.todo import Todo
|
|
from app.schemas.todo import TodoCreate, TodoUpdate, TodoResponse
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("", response_model=List[TodoResponse])
|
|
def read_todos(
|
|
skip: int = Query(0, ge=0),
|
|
limit: int = Query(100, ge=1, le=100),
|
|
db: Session = Depends(get_db)
|
|
):
|
|
"""
|
|
Retrieve all todo items with pagination support.
|
|
"""
|
|
todos = db.query(Todo).offset(skip).limit(limit).all()
|
|
return todos
|
|
|
|
|
|
@router.post("", response_model=TodoResponse, status_code=status.HTTP_201_CREATED)
|
|
def create_todo(todo_in: TodoCreate, db: Session = Depends(get_db)):
|
|
"""
|
|
Create a new todo item.
|
|
"""
|
|
db_todo = Todo(**todo_in.model_dump())
|
|
db.add(db_todo)
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
|
|
@router.get("/{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=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)
|
|
):
|
|
"""
|
|
Update a 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"
|
|
)
|
|
|
|
# Update only provided fields
|
|
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)
|
|
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
|
|
"""
|
|
Delete a 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"
|
|
)
|
|
|
|
db.delete(db_todo)
|
|
db.commit()
|
|
return None |