
- Setup FastAPI project structure - Create SQLAlchemy models and database connection - Implement Alembic migrations - Create CRUD operations for todos - Add API endpoints for todos - Add health endpoint - Update README.md generated with BackendIM... (backend.im)
87 lines
2.1 KiB
Python
87 lines
2.1 KiB
Python
from typing import Any, List, Optional
|
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app import crud, schemas
|
|
from app.db.session import get_db
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("/", response_model=List[schemas.todo.Todo])
|
|
def read_todos(
|
|
db: Session = Depends(get_db),
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
completed: Optional[bool] = None
|
|
) -> Any:
|
|
"""
|
|
Retrieve todos. Can filter by completion status.
|
|
"""
|
|
if completed is not None:
|
|
# Example of filtering logic could be implemented here
|
|
# For now, we just return all todos
|
|
pass
|
|
todos = crud.todo.get_multi(db, skip=skip, limit=limit)
|
|
return todos
|
|
|
|
|
|
@router.post("/", response_model=schemas.todo.Todo)
|
|
def create_todo(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
todo_in: schemas.todo.TodoCreate,
|
|
) -> Any:
|
|
"""
|
|
Create new todo.
|
|
"""
|
|
todo = crud.todo.create(db=db, obj_in=todo_in)
|
|
return todo
|
|
|
|
|
|
@router.get("/{todo_id}", response_model=schemas.todo.Todo)
|
|
def read_todo(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
todo_id: int,
|
|
) -> Any:
|
|
"""
|
|
Get todo by ID.
|
|
"""
|
|
todo = crud.todo.get(db=db, id=todo_id)
|
|
if not todo:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
return todo
|
|
|
|
|
|
@router.put("/{todo_id}", response_model=schemas.todo.Todo)
|
|
def update_todo(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
todo_id: int,
|
|
todo_in: schemas.todo.TodoUpdate,
|
|
) -> Any:
|
|
"""
|
|
Update a todo.
|
|
"""
|
|
todo = crud.todo.get(db=db, id=todo_id)
|
|
if not todo:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
todo = crud.todo.update(db=db, db_obj=todo, obj_in=todo_in)
|
|
return todo
|
|
|
|
|
|
@router.delete("/{todo_id}", response_model=schemas.todo.Todo)
|
|
def delete_todo(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
todo_id: int,
|
|
) -> Any:
|
|
"""
|
|
Delete a todo.
|
|
"""
|
|
todo = crud.todo.get(db=db, id=todo_id)
|
|
if not todo:
|
|
raise HTTPException(status_code=404, detail="Todo not found")
|
|
todo = crud.todo.remove(db=db, id=todo_id)
|
|
return todo |