-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcategories.py
More file actions
68 lines (57 loc) · 2.19 KB
/
Copy pathcategories.py
File metadata and controls
68 lines (57 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import logging
from typing import Annotated
from fastapi import APIRouter, Depends, Query
from database import Database
from dependencies import RequiredAppHeader, get_api_key, get_db
from exceptions import DataNotFoundError
from models.category import CategoryInput, CategoryOutput
from models.responses import IdResponse
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/v2/categories", tags=["Categories"])
@router.get(
"",
summary="List categories",
description="Retrieve categories for an application.",
)
async def get_categories(
_api_key: Annotated[str, Depends(get_api_key)],
db: Annotated[Database, Depends(get_db)],
x_application: RequiredAppHeader,
parent_id: Annotated[str | None, Query(description="Filter by parent category ID")] = None,
) -> list[CategoryOutput]:
"""List categories for an application."""
if not await db.application.exists(x_application):
raise DataNotFoundError(f"Application '{x_application}' not found")
return await db.category.get_all(application=x_application, parent_id=parent_id)
@router.get(
"/{category_id}",
summary="Get category",
description="Retrieve a category and its direct child categories by ID.",
)
async def get_category(
category_id: str,
_api_key: Annotated[str, Depends(get_api_key)],
db: Annotated[Database, Depends(get_db)],
) -> CategoryOutput:
"""Get a category with its children by ID."""
category = await db.category.get_by_id(category_id)
if category is None:
raise DataNotFoundError(f"Category '{category_id}' not found")
return category
@router.post(
"",
status_code=201,
summary="Create category",
description="Create a new category for an application.",
)
async def create_category(
data: CategoryInput,
_api_key: Annotated[str, Depends(get_api_key)],
db: Annotated[Database, Depends(get_db)],
x_application: RequiredAppHeader,
) -> IdResponse:
"""Create a new category."""
if not await db.application.exists(x_application):
raise DataNotFoundError(f"Application '{x_application}' not found")
category_id = await db.category.create(data, application=x_application)
return IdResponse(id=category_id)