Files
taiji-AI-PAD/services/data-ingestion/app/routes/rapidapi.py
T
2025-12-24 11:03:53 +00:00

62 lines
2.1 KiB
Python

"""RapidAPI integration endpoints."""
import structlog
from fastapi import APIRouter, BackgroundTasks, HTTPException
from schemas import RapidAPIRequest
from app.metrics import rapidapi_endpoints_synced, rapidapi_sync_total
from app.state import get_state
logger = structlog.get_logger(__name__)
router = APIRouter(prefix="/rapidapi", tags=["rapidapi"])
@router.post("/sync")
async def sync_endpoints(
background_tasks: BackgroundTasks,
category: str | None = None,
limit: int = 100,
) -> dict:
"""Trigger a background sync job for RapidAPI endpoints."""
state = get_state()
client = state.rapidapi_client
if not client:
raise HTTPException(status_code=500, detail="RapidAPI客户端未初始化")
async def _sync_task() -> None:
try:
result = await client.sync_endpoints(category=category, limit=limit)
status = result.get("status", "error")
rapidapi_sync_total.labels(status=status).inc()
if status == "success":
rapidapi_endpoints_synced.set(result.get("synced", 0))
else:
logger.error("RapidAPI同步失败", result=result)
except Exception as exc: # pragma: no cover - background task
rapidapi_sync_total.labels(status="error").inc()
logger.error("后台同步任务失败", error=str(exc))
background_tasks.add_task(_sync_task)
return {"message": "RapidAPI端点同步已启动", "category": category, "limit": limit}
@router.post("/test")
async def test_endpoint(request: RapidAPIRequest) -> dict:
"""Proxy a test call to a RapidAPI endpoint."""
state = get_state()
client = state.rapidapi_client
if not client:
raise HTTPException(status_code=500, detail="RapidAPI客户端未初始化")
try:
return await client.test_endpoint(
endpoint=request.endpoint,
method=request.method,
params=request.params,
headers=request.headers,
)
except Exception as exc:
logger.error("测试RapidAPI端点失败", error=str(exc))
raise HTTPException(status_code=500, detail=str(exc)) from exc