Automated Action 5e499461d7 Create simple FastAPI Todo application
- Set up project structure with FastAPI
- Create Todo model with SQLAlchemy
- Set up Alembic for database migrations
- Implement CRUD operations for todos
- Add health endpoint
- Update README with setup and usage instructions

generated with BackendIM... (backend.im)
2025-05-13 05:00:15 +00:00

91 lines
2.0 KiB
Python

from typing import List, Any
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app import crud
from app.db.session import get_db
from app.schemas.todo import Todo, TodoCreate, TodoUpdate
router = APIRouter()
@router.get("/", response_model=List[Todo])
def read_todos(
skip: int = 0, limit: int = 100, db: Session = Depends(get_db)
) -> Any:
"""
Retrieve all todos.
"""
todos = crud.get_todos(db=db, skip=skip, limit=limit)
return todos
@router.post("/", response_model=Todo, status_code=status.HTTP_201_CREATED)
def create_todo(
*,
todo_in: TodoCreate,
db: Session = Depends(get_db)
) -> Any:
"""
Create new todo.
"""
todo = crud.create_todo(db=db, todo=todo_in)
return todo
@router.get("/{todo_id}", response_model=Todo)
def read_todo(
*,
todo_id: int,
db: Session = Depends(get_db)
) -> Any:
"""
Get todo by ID.
"""
todo = crud.get_todo(db=db, todo_id=todo_id)
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Todo not found"
)
return todo
@router.put("/{todo_id}", response_model=Todo)
def update_todo(
*,
todo_id: int,
todo_in: TodoUpdate,
db: Session = Depends(get_db)
) -> Any:
"""
Update a todo.
"""
todo = crud.get_todo(db=db, todo_id=todo_id)
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Todo not found"
)
todo = crud.update_todo(db=db, todo_id=todo_id, todo=todo_in)
return todo
@router.delete("/{todo_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_todo(
*,
todo_id: int,
db: Session = Depends(get_db)
) -> Any:
"""
Delete a todo.
"""
todo = crud.get_todo(db=db, todo_id=todo_id)
if not todo:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Todo not found"
)
crud.delete_todo(db=db, todo_id=todo_id)
return None