
- Set up project structure with FastAPI app - Implement SQLAlchemy models and async database connection - Create CRUD endpoints for items resource - Add health endpoint for monitoring - Configure Alembic for database migrations - Create comprehensive documentation generated with BackendIM... (backend.im)
119 lines
3.4 KiB
Python
119 lines
3.4 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy.future import select
|
|
from typing import List
|
|
|
|
from app.db.database import get_db
|
|
from app.models.item import Item
|
|
from app.schemas.item import ItemCreate, ItemResponse, ItemUpdate
|
|
|
|
router = APIRouter(tags=["items"])
|
|
|
|
@router.post("/items", response_model=ItemResponse, status_code=status.HTTP_201_CREATED)
|
|
async def create_item(item: ItemCreate, db: AsyncSession = Depends(get_db)):
|
|
"""
|
|
Create a new item.
|
|
|
|
Args:
|
|
item: The item data to create
|
|
db: Database session
|
|
|
|
Returns:
|
|
The created item
|
|
"""
|
|
db_item = Item(**item.model_dump())
|
|
db.add(db_item)
|
|
await db.commit()
|
|
await db.refresh(db_item)
|
|
return db_item
|
|
|
|
@router.get("/items", response_model=List[ItemResponse])
|
|
async def read_items(skip: int = 0, limit: int = 100, db: AsyncSession = Depends(get_db)):
|
|
"""
|
|
Retrieve all items with pagination.
|
|
|
|
Args:
|
|
skip: Number of items to skip (for pagination)
|
|
limit: Maximum number of items to return
|
|
db: Database session
|
|
|
|
Returns:
|
|
List of items
|
|
"""
|
|
result = await db.execute(select(Item).offset(skip).limit(limit))
|
|
items = result.scalars().all()
|
|
return items
|
|
|
|
@router.get("/items/{item_id}", response_model=ItemResponse)
|
|
async def read_item(item_id: int, db: AsyncSession = Depends(get_db)):
|
|
"""
|
|
Retrieve a specific item by ID.
|
|
|
|
Args:
|
|
item_id: The ID of the item to retrieve
|
|
db: Database session
|
|
|
|
Returns:
|
|
The requested item if found
|
|
|
|
Raises:
|
|
HTTPException: If the item is not found
|
|
"""
|
|
result = await db.execute(select(Item).filter(Item.id == item_id))
|
|
item = result.scalars().first()
|
|
if item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
return item
|
|
|
|
@router.put("/items/{item_id}", response_model=ItemResponse)
|
|
async def update_item(item_id: int, item: ItemUpdate, db: AsyncSession = Depends(get_db)):
|
|
"""
|
|
Update an existing item.
|
|
|
|
Args:
|
|
item_id: The ID of the item to update
|
|
item: The updated item data
|
|
db: Database session
|
|
|
|
Returns:
|
|
The updated item
|
|
|
|
Raises:
|
|
HTTPException: If the item is not found
|
|
"""
|
|
result = await db.execute(select(Item).filter(Item.id == item_id))
|
|
db_item = result.scalars().first()
|
|
if db_item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
|
|
update_data = item.model_dump(exclude_unset=True)
|
|
for key, value in update_data.items():
|
|
setattr(db_item, key, value)
|
|
|
|
await db.commit()
|
|
await db.refresh(db_item)
|
|
return db_item
|
|
|
|
@router.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
async def delete_item(item_id: int, db: AsyncSession = Depends(get_db)):
|
|
"""
|
|
Delete an item.
|
|
|
|
Args:
|
|
item_id: The ID of the item to delete
|
|
db: Database session
|
|
|
|
Returns:
|
|
No content on successful deletion
|
|
|
|
Raises:
|
|
HTTPException: If the item is not found
|
|
"""
|
|
result = await db.execute(select(Item).filter(Item.id == item_id))
|
|
db_item = result.scalars().first()
|
|
if db_item is None:
|
|
raise HTTPException(status_code=404, detail="Item not found")
|
|
|
|
await db.delete(db_item)
|
|
await db.commit()
|
|
return None |