Spaces:
Building
Building
from fastapi import APIRouter, HTTPException, Request, Depends | |
from config_provider import get_config, ServiceConfig | |
from service_config import ServiceConfig | |
import json | |
router = APIRouter() | |
def list_apis(config: ServiceConfig = Depends(get_config)): | |
return config.apis | |
async def add_api(request: Request, config: ServiceConfig = Depends(get_config)): | |
data = await request.json() | |
api_name = data.get("api_name") | |
api_data = data.get("api_data") | |
if not api_name or not api_data: | |
raise HTTPException(status_code=400, detail="api_name and api_data are required") | |
if api_name in config.apis: | |
raise HTTPException(status_code=400, detail="API with this name already exists") | |
config.apis[api_name] = api_data | |
with open(config.config_path, "w", encoding="utf-8") as f: | |
json.dump(config, f, indent=2) | |
return {"message": f"API {api_name} added"} | |
async def update_api(request: Request, config: ServiceConfig = Depends(get_config)): | |
data = await request.json() | |
api_name = data.get("api_name") | |
api_data = data.get("api_data") | |
if not api_name or not api_data: | |
raise HTTPException(status_code=400, detail="api_name and api_data are required") | |
if api_name not in config.apis: | |
raise HTTPException(status_code=404, detail="API not found") | |
config.apis[api_name] = api_data | |
with open(config.config_path, "w", encoding="utf-8") as f: | |
json.dump(config, f, indent=2) | |
return {"message": f"API {api_name} updated"} | |
async def delete_api(request: Request, config: ServiceConfig = Depends(get_config)): | |
data = await request.json() | |
api_name = data.get("api_name") | |
if not api_name: | |
raise HTTPException(status_code=400, detail="api_name is required") | |
if api_name not in config.apis: | |
raise HTTPException(status_code=404, detail="API not found") | |
# Check if API is used in any intent | |
used_in = [] | |
for project_name, project in config.projects.items(): | |
for version in project.get("versions", []): | |
for intent in version.get("intents", []): | |
if intent.get("action") == api_name: | |
used_in.append(f"{project_name} β v{version.get('version_number')} β {intent.get('name')}") | |
if used_in: | |
raise HTTPException( | |
status_code=400, | |
detail=f"API '{api_name}' is used in intents: {', '.join(used_in)}. Cannot delete." | |
) | |
del config.apis[api_name] | |
with open(config.config_path, "w", encoding="utf-8") as f: | |
json.dump(config, f, indent=2) | |
return {"message": f"API {api_name} deleted"} | |