Automated Action bf1393d643 Create Simple Todo API with FastAPI and SQLite
- Set up FastAPI project structure
- Configure SQLAlchemy with SQLite
- Create Todo model and schemas
- Implement CRUD operations
- Add API endpoints for Todo management
- Configure Alembic for database migrations
- Add health check endpoint
- Add comprehensive documentation
2025-05-17 20:16:30 +00:00

55 lines
1.8 KiB
Python

from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
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 TodoCreate, TodoResponse, TodoUpdate
router = APIRouter()
@router.get("/todos/", response_model=List[TodoResponse])
def read_todos(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
"""Get all todos with optional pagination"""
todos = todo_crud.get_todos(db, skip=skip, limit=limit)
return todos
@router.post(
"/todos/", response_model=TodoResponse, status_code=status.HTTP_201_CREATED
)
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
"""Create a new todo"""
return todo_crud.create_todo(db=db, todo=todo)
@router.get("/todos/{todo_id}", response_model=TodoResponse)
def read_todo(todo_id: int, db: Session = Depends(get_db)):
"""Get a specific todo by ID"""
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("/todos/{todo_id}", response_model=TodoResponse)
def update_todo(todo_id: int, todo: TodoUpdate, db: Session = Depends(get_db)):
"""Update a todo by ID"""
db_todo = todo_crud.update_todo(db, todo_id=todo_id, todo=todo)
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
return db_todo
@router.delete(
"/todos/{todo_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None
)
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
"""Delete a todo by ID"""
success = todo_crud.delete_todo(db, todo_id=todo_id)
if not success:
raise HTTPException(status_code=404, detail="Todo not found")
return None