diff --git a/app/api/api.py b/app/api/api.py new file mode 100644 index 0000000..1fd0318 --- /dev/null +++ b/app/api/api.py @@ -0,0 +1,6 @@ +from fastapi import APIRouter +from app.api.endpoints import todos + +api_router = APIRouter() + +api_router.include_router(todos.router, prefix="/todos", tags=["todos"]) \ No newline at end of file diff --git a/app/api/endpoints/__init__.py b/app/api/endpoints/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/endpoints/todos.py b/app/api/endpoints/todos.py new file mode 100644 index 0000000..17bdde2 --- /dev/null +++ b/app/api/endpoints/todos.py @@ -0,0 +1,72 @@ +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, TodoUpdate, TodoResponse + +router = APIRouter() + + +@router.get("/", response_model=List[TodoResponse]) +def get_todos(db: Session = Depends(get_db)): + """Get all todos""" + todos = db.query(Todo).all() + return todos + + +@router.post("/", response_model=TodoResponse, status_code=status.HTTP_201_CREATED) +def create_todo(todo: TodoCreate, db: Session = Depends(get_db)): + """Create a new todo""" + db_todo = Todo(**todo.dict()) + db.add(db_todo) + db.commit() + db.refresh(db_todo) + return db_todo + + +@router.get("/{todo_id}", response_model=TodoResponse) +def get_todo(todo_id: int, db: Session = Depends(get_db)): + """Get a specific todo by ID""" + todo = db.query(Todo).filter(Todo.id == todo_id).first() + if not todo: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Todo with id {todo_id} not found" + ) + return todo + + +@router.put("/{todo_id}", response_model=TodoResponse) +def update_todo(todo_id: int, todo_update: TodoUpdate, db: Session = Depends(get_db)): + """Update a specific todo by ID""" + todo = db.query(Todo).filter(Todo.id == todo_id).first() + if not todo: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Todo with id {todo_id} not found" + ) + + # Update only provided fields + 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("/{todo_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_todo(todo_id: int, db: Session = Depends(get_db)): + """Delete a specific todo by ID""" + todo = db.query(Todo).filter(Todo.id == todo_id).first() + if not todo: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail=f"Todo with id {todo_id} not found" + ) + + db.delete(todo) + db.commit() + return None \ No newline at end of file diff --git a/app/models/__init__.py b/app/models/__init__.py index e69de29..a5b88be 100644 --- a/app/models/__init__.py +++ b/app/models/__init__.py @@ -0,0 +1,3 @@ +from .todo import Todo + +__all__ = ["Todo"] \ No newline at end of file diff --git a/app/models/todo.py b/app/models/todo.py new file mode 100644 index 0000000..fc59e77 --- /dev/null +++ b/app/models/todo.py @@ -0,0 +1,14 @@ +from sqlalchemy import Column, Integer, String, Text, Boolean, DateTime +from sqlalchemy.sql import func +from app.db.base import Base + + +class Todo(Base): + __tablename__ = "todos" + + id = Column(Integer, primary_key=True, index=True) + title = Column(String(255), nullable=False, index=True) + description = Column(Text, nullable=True) + completed = Column(Boolean, default=False, nullable=False) + created_at = Column(DateTime(timezone=True), server_default=func.now()) + updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now()) \ No newline at end of file diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..56f0064 --- /dev/null +++ b/app/schemas/__init__.py @@ -0,0 +1,3 @@ +from .todo import TodoBase, TodoCreate, TodoUpdate, TodoResponse + +__all__ = ["TodoBase", "TodoCreate", "TodoUpdate", "TodoResponse"] \ No newline at end of file diff --git a/app/schemas/todo.py b/app/schemas/todo.py new file mode 100644 index 0000000..ab090a2 --- /dev/null +++ b/app/schemas/todo.py @@ -0,0 +1,28 @@ +from datetime import datetime +from typing import Optional +from pydantic import BaseModel + + +class TodoBase(BaseModel): + title: str + description: Optional[str] = None + completed: bool = False + + +class TodoCreate(TodoBase): + pass + + +class TodoUpdate(BaseModel): + title: Optional[str] = None + description: Optional[str] = None + completed: Optional[bool] = None + + +class TodoResponse(TodoBase): + id: int + created_at: datetime + updated_at: datetime + + class Config: + from_attributes = True \ No newline at end of file diff --git a/main.py b/main.py index ecb0a26..4cc50fc 100644 --- a/main.py +++ b/main.py @@ -3,6 +3,7 @@ from fastapi.middleware.cors import CORSMiddleware from sqlalchemy.orm import Session from app.db.session import get_db, engine from app.db.base import Base +from app.api.api import api_router # Create database tables Base.metadata.create_all(bind=engine) @@ -26,6 +27,9 @@ app.add_middleware( allow_headers=["*"], ) +# Include API router +app.include_router(api_router, prefix="/api/v1") + @app.get("/") async def root(): diff --git a/migrations/env.py b/migrations/env.py index e3b87c6..6baf478 100644 --- a/migrations/env.py +++ b/migrations/env.py @@ -14,7 +14,7 @@ sys.path.insert(0, str(Path(__file__).parent.parent)) from app.db.base import Base # Import all models so they are available to Alembic -from app.models.todo import Todo +from app.models import Todo # noqa: F401 # this is the Alembic Config object, which provides # access to the values within the .ini file in use.