Spaces:
Sleeping
Sleeping
File size: 2,679 Bytes
7183ec8 |
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 69 70 71 72 73 74 75 |
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional # Import Optional
from .. import crud, schemas # Use relative imports
from ..database import get_db # Use relative import
router = APIRouter()
@router.get("/categories/", response_model=List[schemas.KeyCategory])
def read_key_categories(
skip: int = Query(0, ge=0),
limit: int = Query(100, ge=0, le=100),
db: Session = Depends(get_db)
):
"""
Retrieve a list of key categories.
"""
categories = crud.get_key_categories(db, skip=skip, limit=limit)
return categories
@router.post("/categories/", response_model=schemas.KeyCategory)
def create_key_category(
category: schemas.KeyCategoryCreate,
db: Session = Depends(get_db)
):
"""
Create a new key category.
"""
# Check if category with the same name already exists
db_category = crud.get_key_category_by_name(db, name=category.name)
if db_category:
raise HTTPException(status_code=400, detail="Key Category with this name already exists")
# Create the category using the CRUD function
return crud.create_key_category(db=db, name=category.name, type=category.type, tags=category.tags, metadata=category.metadata)
@router.get("/instances/", response_model=List[schemas.APIKey])
def read_api_keys(
category_id: Optional[int] = Query(None, ge=1), # Optional filter by category ID
status: Optional[str] = Query(None, pattern="^(active|inactive)$"), # Optional filter by status
skip: int = Query(0, ge=0),
limit: int = Query(100, ge=0, le=100),
db: Session = Depends(get_db)
):
"""
Retrieve a list of API key instances, optionally filtered by category or status.
"""
keys = crud.get_api_keys(db, category_id=category_id, status=status, skip=skip, limit=limit)
return keys
@router.post("/instances/", response_model=schemas.APIKey)
def create_api_key(
api_key: schemas.APIKeyCreate,
db: Session = Depends(get_db)
):
"""
Create a new API key instance under a specific category.
"""
# Check if the category_id exists
category = crud.get_key_category(db, category_id=api_key.category_id)
if not category:
raise HTTPException(status_code=404, detail=f"Key Category with ID {api_key.category_id} not found")
# Create the API key instance using the CRUD function
return crud.create_api_key(
db=db,
value=api_key.value,
category_id=api_key.category_id,
status=api_key.status,
metadata=api_key.metadata
)
# TODO: Add other CRUD endpoints for key categories and API keys (GET by ID, PUT, DELETE)
|