Automated Action 538a985c8e Build e-commerce API with FastAPI and SQLite
Create a complete e-commerce application with the following features:
- User authentication and authorization
- Product and category management
- Shopping cart functionality
- Order processing
- Database migrations with Alembic
- Comprehensive documentation
2025-05-26 11:05:27 +00:00

105 lines
2.8 KiB
Python

from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.core.deps import get_current_active_superuser, get_current_active_user, get_db
from app.models.user import User
from app.schemas.category import Category, CategoryCreate, CategoryUpdate
from app.services import category as category_service
router = APIRouter()
@router.get("/", response_model=List[Category])
def read_categories(
db: Session = Depends(get_db),
skip: int = 0,
limit: int = 100,
current_user: User = Depends(get_current_active_user),
) -> Any:
"""
Retrieve categories.
"""
categories = category_service.get_multi(db, skip=skip, limit=limit)
return categories
@router.post("/", response_model=Category)
def create_category(
*,
db: Session = Depends(get_db),
category_in: CategoryCreate,
current_user: User = Depends(get_current_active_superuser),
) -> Any:
"""
Create new category.
"""
category = category_service.get_by_name(db, name=category_in.name)
if category:
raise HTTPException(
status_code=400,
detail="A category with this name already exists",
)
category = category_service.create(db, obj_in=category_in)
return category
@router.get("/{category_id}", response_model=Category)
def read_category(
*,
db: Session = Depends(get_db),
category_id: str,
current_user: User = Depends(get_current_active_user),
) -> Any:
"""
Get category by ID.
"""
category = category_service.get_by_id(db, category_id=category_id)
if not category:
raise HTTPException(
status_code=404,
detail="Category not found",
)
return category
@router.put("/{category_id}", response_model=Category)
def update_category(
*,
db: Session = Depends(get_db),
category_id: str,
category_in: CategoryUpdate,
current_user: User = Depends(get_current_active_superuser),
) -> Any:
"""
Update a category.
"""
category = category_service.get_by_id(db, category_id=category_id)
if not category:
raise HTTPException(
status_code=404,
detail="Category not found",
)
category = category_service.update(db, db_obj=category, obj_in=category_in)
return category
@router.delete("/{category_id}", response_model=Category)
def delete_category(
*,
db: Session = Depends(get_db),
category_id: str,
current_user: User = Depends(get_current_active_superuser),
) -> Any:
"""
Delete a category.
"""
category = category_service.get_by_id(db, category_id=category_id)
if not category:
raise HTTPException(
status_code=404,
detail="Category not found",
)
category = category_service.delete(db, category_id=category_id)
return category