
- Set up project structure with proper directory layout - Implemented SQLite database with SQLAlchemy ORM - Created Todo model with CRUD operations - Added Alembic for database migrations - Implemented RESTful API endpoints for todos - Added health check endpoint - Configured CORS for all origins - Created comprehensive documentation - Added linting with Ruff
72 lines
2.2 KiB
Python
72 lines
2.2 KiB
Python
from typing import List, Optional
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
from pydantic import BaseModel
|
|
from app.db.session import get_db
|
|
from app.models.todo import Todo
|
|
|
|
router = APIRouter()
|
|
|
|
class TodoCreate(BaseModel):
|
|
title: str
|
|
description: Optional[str] = None
|
|
|
|
class TodoUpdate(BaseModel):
|
|
title: Optional[str] = None
|
|
description: Optional[str] = None
|
|
completed: Optional[bool] = None
|
|
|
|
class TodoResponse(BaseModel):
|
|
id: int
|
|
title: str
|
|
description: Optional[str] = None
|
|
completed: bool
|
|
created_at: str
|
|
updated_at: Optional[str] = None
|
|
|
|
class Config:
|
|
from_attributes = True
|
|
|
|
@router.post("/todos", response_model=TodoResponse)
|
|
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
|
|
db_todo = Todo(title=todo.title, description=todo.description)
|
|
db.add(db_todo)
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
@router.get("/todos", response_model=List[TodoResponse])
|
|
def get_todos(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
|
todos = db.query(Todo).offset(skip).limit(limit).all()
|
|
return todos
|
|
|
|
@router.get("/todos/{todo_id}", response_model=TodoResponse)
|
|
def get_todo(todo_id: int, db: Session = Depends(get_db)):
|
|
todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
|
if todo is None:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
return todo
|
|
|
|
@router.put("/todos/{todo_id}", response_model=TodoResponse)
|
|
def update_todo(todo_id: int, todo_update: TodoUpdate, db: Session = Depends(get_db)):
|
|
todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
|
if todo is None:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
|
|
update_data = todo_update.dict(exclude_unset=True)
|
|
for field, value in update_data.items():
|
|
setattr(todo, field, value)
|
|
|
|
db.commit()
|
|
db.refresh(todo)
|
|
return todo
|
|
|
|
@router.delete("/todos/{todo_id}")
|
|
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
|
|
todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
|
if todo is None:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
|
|
db.delete(todo)
|
|
db.commit()
|
|
return {"message": "Todo deleted successfully"} |