""" Core API Client - Reusable HTTP client for YAZ platform """ import httpx import orjson from typing import Any, Dict, List, Optional, Union from pathlib import Path import structlog logger = structlog.get_logger(__name__) class APIError(Exception): """API request error""" def __init__( self, message: str, status_code: Optional[int] = None, response_data: Optional[Dict] = None ): super().__init__(message) self.status_code = status_code self.response_data = response_data class APIClient: """HTTP client wrapper with error handling and JSON serialization""" def __init__( self, base_url: str = "http://localhost:8000", timeout: float = 60.0, headers: Optional[Dict[str, str]] = None, ): self.base_url = base_url.rstrip("/") self.timeout = timeout default_headers = { "Content-Type": "application/json", "Accept": "application/json", "User-Agent": "YAZ-Platform/1.0", } if headers: default_headers.update(headers) self.client = httpx.Client( base_url=self.base_url, timeout=self.timeout, headers=default_headers ) def _handle_response(self, response: httpx.Response) -> Dict[str, Any]: """Handle HTTP response with error checking""" try: response.raise_for_status() if response.headers.get("content-type", "").startswith("application/json"): return response.json() else: return {"data": response.text, "status": "success"} except httpx.HTTPStatusError as e: error_data = None try: error_data = response.json() except Exception: error_data = {"error": response.text} logger.error(f"HTTP {response.status_code}: {error_data}") raise APIError( f"API request failed: {e}", status_code=response.status_code, response_data=error_data, ) from e def get(self, endpoint: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: """Make GET request""" response = self.client.get(endpoint, params=params) return self._handle_response(response) def post( self, endpoint: str, data: Optional[Dict[str, Any]] = None, **kwargs ) -> Dict[str, Any]: """Make POST request with JSON data""" # Merge kwargs into data if data is None: data = kwargs else: data.update(kwargs) # Use orjson for better performance json_data = orjson.dumps(data) if data else None response = self.client.post( endpoint, content=json_data, headers={"Content-Type": "application/json"} if json_data else None, ) return self._handle_response(response) def upload_fileobj( self, endpoint: str, file_obj, filename: str, field_name: str = "file" ) -> Dict[str, Any]: """Upload file object via POST request""" files = {field_name: (filename, file_obj, "application/octet-stream")} # Remove JSON content-type for file uploads headers = {k: v for k, v in self.client.headers.items() if k.lower() != "content-type"} response = self.client.post(endpoint, files=files, headers=headers) return self._handle_response(response) def close(self): """Close the HTTP client""" self.client.close() # Global client instance api_client = APIClient() # Convenience functions def get(endpoint: str, **kwargs) -> Dict[str, Any]: return api_client.get(endpoint, **kwargs) def post(endpoint: str, **kwargs) -> Dict[str, Any]: return api_client.post(endpoint, **kwargs)