Automated Action db2997cc83 Create FastAPI todo backend with SQLite
Generated with and Co-Authored by [BackendIM](https://backend.im)
2025-05-11 16:39:38 +00:00

83 lines
1.8 KiB
Python

from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app import crud, schemas
from app.api import deps
router = APIRouter()
@router.get("/", response_model=List[schemas.Todo])
def read_todos(
db: Session = Depends(deps.get_db),
skip: int = 0,
limit: int = 100,
) -> Any:
"""
Retrieve todos.
"""
todos = crud.todo.get_multi(db, skip=skip, limit=limit)
return todos
@router.post("/", response_model=schemas.Todo)
def create_todo(
*,
db: Session = Depends(deps.get_db),
todo_in: schemas.TodoCreate,
) -> Any:
"""
Create new todo.
"""
todo = crud.todo.create(db=db, obj_in=todo_in)
return todo
@router.get("/{id}", response_model=schemas.Todo)
def read_todo(
*,
db: Session = Depends(deps.get_db),
id: int,
) -> Any:
"""
Get todo by ID.
"""
todo = crud.todo.get(db=db, id=id)
if not todo:
raise HTTPException(status_code=404, detail="Todo not found")
return todo
@router.put("/{id}", response_model=schemas.Todo)
def update_todo(
*,
db: Session = Depends(deps.get_db),
id: int,
todo_in: schemas.TodoUpdate,
) -> Any:
"""
Update a todo.
"""
todo = crud.todo.get(db=db, id=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("/{id}", response_model=schemas.Todo)
def delete_todo(
*,
db: Session = Depends(deps.get_db),
id: int,
) -> Any:
"""
Delete a todo.
"""
todo = crud.todo.get(db=db, id=id)
if not todo:
raise HTTPException(status_code=404, detail="Todo not found")
todo = crud.todo.remove(db=db, id=id)
return todo