Files
ContecMonitor/fiveparaminte-main/api_client.py
T

39 lines
1.2 KiB
Python

import httpx
import logging
from typing import Optional
from schemas import NormalizedVitals
from config import settings
logger = logging.getLogger(__name__)
async def forward_vitals_to_api(vitals: NormalizedVitals) -> bool:
"""
Attempts to POST the normalized vitals to the configured target API.
Returns True if successful, False otherwise.
"""
url = settings.target_api_url
headers = {"Content-Type": "application/json"}
if settings.api_token:
headers["Authorization"] = f"Bearer {settings.api_token}"
try:
async with httpx.AsyncClient(timeout=10.0) as client:
response = await client.post(
url,
json=vitals.model_dump(mode="json"),
headers=headers
)
response.raise_for_status()
logger.info(f"Successfully forwarded vitals for device {vitals.device_id}")
return True
except httpx.HTTPStatusError as e:
logger.error(f"API returned HTTP {e.response.status_code}: {e.response.text}")
except httpx.RequestError as e:
logger.error(f"Request to API failed: {e}")
except Exception as e:
logger.error(f"Unexpected error forwarding to API: {e}")
return False