
- Add project structure with FastAPI, SQLAlchemy, and Alembic - Implement Todo model with CRUD operations - Add REST API endpoints for todo management - Configure SQLite database with migrations - Include health check and API documentation endpoints - Add CORS middleware for all origins - Format code with Ruff
45 lines
1.5 KiB
Python
45 lines
1.5 KiB
Python
from typing import List
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.crud import todo as todo_crud
|
|
from app.db.session import get_db
|
|
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, db: Session = Depends(get_db)):
|
|
todos = todo_crud.get_todos(db, skip=skip, limit=limit)
|
|
return todos
|
|
|
|
|
|
@router.post("/", response_model=Todo)
|
|
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
|
|
return todo_crud.create_todo(db=db, todo=todo)
|
|
|
|
|
|
@router.get("/{todo_id}", response_model=Todo)
|
|
def read_todo(todo_id: int, db: Session = Depends(get_db)):
|
|
db_todo = todo_crud.get_todo(db, todo_id=todo_id)
|
|
if db_todo is None:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
return db_todo
|
|
|
|
|
|
@router.put("/{todo_id}", response_model=Todo)
|
|
def update_todo(todo_id: int, todo_update: TodoUpdate, db: Session = Depends(get_db)):
|
|
db_todo = todo_crud.update_todo(db, todo_id=todo_id, todo_update=todo_update)
|
|
if db_todo is None:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
return db_todo
|
|
|
|
|
|
@router.delete("/{todo_id}")
|
|
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
|
|
success = todo_crud.delete_todo(db, todo_id=todo_id)
|
|
if not success:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
return {"message": "Todo deleted successfully"}
|