Automated Action e1ed70e281 Create FastAPI Todo API application
- Set up project structure and requirements
- Create database models and connection
- Set up Alembic for migrations
- Implement CRUD operations for todos
- Build RESTful API endpoints
- Update README with project documentation

generated with BackendIM... (backend.im)
2025-05-11 19:49:50 +00:00

73 lines
2.0 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List
from db.database import get_db
from schemas.todo import Todo, TodoCreate, TodoUpdate
from services.todo import (
get_todos,
get_todo,
create_todo,
update_todo,
delete_todo,
)
router = APIRouter(
prefix="/todos",
tags=["todos"],
responses={404: {"description": "Not found"}},
)
@router.get("/", response_model=List[Todo])
def read_todos(
skip: int = Query(0, ge=0, description="Skip the first N items"),
limit: int = Query(100, ge=1, le=100, description="Limit the number of items returned"),
db: Session = Depends(get_db)
):
"""
Get all todos with pagination.
"""
todos = get_todos(db, skip=skip, limit=limit)
return todos
@router.post("/", response_model=Todo, status_code=status.HTTP_201_CREATED)
def create_new_todo(todo: TodoCreate, db: Session = Depends(get_db)):
"""
Create a new todo.
"""
return create_todo(db=db, todo=todo)
@router.get("/{todo_id}", response_model=Todo)
def read_todo(todo_id: int, db: Session = Depends(get_db)):
"""
Get a specific todo by ID.
"""
db_todo = 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("/{todo_id}", response_model=Todo)
def update_existing_todo(todo_id: int, todo: TodoUpdate, db: Session = Depends(get_db)):
"""
Update an existing todo.
"""
db_todo = update_todo(db=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("/{todo_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_existing_todo(todo_id: int, db: Session = Depends(get_db)):
"""
Delete a todo.
"""
success = delete_todo(db=db, todo_id=todo_id)
if not success:
raise HTTPException(status_code=404, detail="Todo not found")
return None