Automated Action f047098f40 Create FastAPI REST API with SQLite database
- Set up project structure with FastAPI and SQLAlchemy
- Configure SQLite database with async support
- Implement CRUD endpoints for items resource
- Add health endpoint for monitoring
- Set up Alembic migrations
- Create comprehensive documentation

generated with BackendIM... (backend.im)
2025-05-14 01:20:38 +00:00

63 lines
2.3 KiB
Python

from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from app.db.session import get_db
from app.models.item import Item
from app.schemas.item import ItemCreate, ItemResponse, ItemUpdate
router = APIRouter()
@router.post("", response_model=ItemResponse, status_code=status.HTTP_201_CREATED)
async def create_item(item_in: ItemCreate, db: AsyncSession = Depends(get_db)):
"""Create a new item."""
db_item = Item(**item_in.model_dump())
db.add(db_item)
await db.commit()
await db.refresh(db_item)
return db_item
@router.get("", response_model=List[ItemResponse])
async def read_items(skip: int = 0, limit: int = 100, db: AsyncSession = Depends(get_db)):
"""Get all items."""
result = await db.execute(select(Item).offset(skip).limit(limit))
items = result.scalars().all()
return items
@router.get("/{item_id}", response_model=ItemResponse)
async def read_item(item_id: int, db: AsyncSession = Depends(get_db)):
"""Get item by ID."""
result = await db.execute(select(Item).filter(Item.id == item_id))
item = result.scalars().first()
if not item:
raise HTTPException(status_code=404, detail="Item not found")
return item
@router.put("/{item_id}", response_model=ItemResponse)
async def update_item(item_id: int, item_in: ItemUpdate, db: AsyncSession = Depends(get_db)):
"""Update an item."""
result = await db.execute(select(Item).filter(Item.id == item_id))
item = result.scalars().first()
if not item:
raise HTTPException(status_code=404, detail="Item not found")
update_data = item_in.model_dump(exclude_unset=True)
for key, value in update_data.items():
setattr(item, key, value)
await db.commit()
await db.refresh(item)
return item
@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_item(item_id: int, db: AsyncSession = Depends(get_db)):
"""Delete an item."""
result = await db.execute(select(Item).filter(Item.id == item_id))
item = result.scalars().first()
if not item:
raise HTTPException(status_code=404, detail="Item not found")
await db.delete(item)
await db.commit()
return None