
Features: - Project structure with FastAPI framework - SQLAlchemy models with SQLite database - Alembic migrations system - CRUD operations for items - API routers with endpoints for items - Health endpoint for monitoring - Error handling and validation - Comprehensive documentation
91 lines
2.0 KiB
Python
91 lines
2.0 KiB
Python
from typing import Any, List, Optional
|
|
|
|
from fastapi import APIRouter, Depends, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app import crud, schemas
|
|
from app.api.errors import ItemNotFoundException
|
|
from app.db.session import get_db
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("", response_model=List[schemas.Item])
|
|
def read_items(
|
|
db: Session = Depends(get_db),
|
|
skip: int = 0,
|
|
limit: int = 100,
|
|
is_active: Optional[bool] = None,
|
|
) -> Any:
|
|
"""
|
|
Retrieve items.
|
|
"""
|
|
if is_active is not None:
|
|
items = crud.item.get_multi_by_active(
|
|
db, skip=skip, limit=limit, is_active=is_active
|
|
)
|
|
else:
|
|
items = crud.item.get_multi(db, skip=skip, limit=limit)
|
|
return items
|
|
|
|
|
|
@router.post("", response_model=schemas.Item, status_code=status.HTTP_201_CREATED)
|
|
def create_item(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
item_in: schemas.ItemCreate,
|
|
) -> Any:
|
|
"""
|
|
Create new item.
|
|
"""
|
|
item = crud.item.create(db=db, obj_in=item_in)
|
|
return item
|
|
|
|
|
|
@router.get("/{item_id}", response_model=schemas.Item)
|
|
def read_item(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
item_id: int,
|
|
) -> Any:
|
|
"""
|
|
Get item by ID.
|
|
"""
|
|
item = crud.item.get(db=db, id=item_id)
|
|
if not item:
|
|
raise ItemNotFoundException(item_id=item_id)
|
|
return item
|
|
|
|
|
|
@router.put("/{item_id}", response_model=schemas.Item)
|
|
def update_item(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
item_id: int,
|
|
item_in: schemas.ItemUpdate,
|
|
) -> Any:
|
|
"""
|
|
Update an item.
|
|
"""
|
|
item = crud.item.get(db=db, id=item_id)
|
|
if not item:
|
|
raise ItemNotFoundException(item_id=item_id)
|
|
item = crud.item.update(db=db, db_obj=item, obj_in=item_in)
|
|
return item
|
|
|
|
|
|
@router.delete("/{item_id}", response_model=schemas.Item)
|
|
def delete_item(
|
|
*,
|
|
db: Session = Depends(get_db),
|
|
item_id: int,
|
|
) -> Any:
|
|
"""
|
|
Delete an item.
|
|
"""
|
|
item = crud.item.get(db=db, id=item_id)
|
|
if not item:
|
|
raise ItemNotFoundException(item_id=item_id)
|
|
item = crud.item.remove(db=db, id=item_id)
|
|
return item
|