Spaces:
Paused

File size: 3,861 Bytes
07612e2
 
 
 
 
 
 
 
579285c
07612e2
579285c
07612e2
 
 
 
5b36da5
 
 
 
07612e2
 
 
 
 
 
 
5b36da5
07612e2
5b36da5
07612e2
 
5b36da5
07612e2
5b36da5
07612e2
5b36da5
07612e2
 
 
5b36da5
07612e2
5b36da5
07612e2
 
5b36da5
07612e2
5b36da5
07612e2
5b36da5
07612e2
 
 
 
5b36da5
07612e2
 
 
 
5b36da5
07612e2
 
 
 
 
 
5b36da5
07612e2
 
 
 
5b36da5
07612e2
5b36da5
07612e2
 
 
 
5b36da5
 
 
 
07612e2
 
 
 
 
 
5b36da5
07612e2
 
5b36da5
07612e2
5b36da5
07612e2
5b36da5
07612e2
 
5b36da5
 
 
 
07612e2
5b36da5
 
07612e2
5b36da5
 
07612e2
 
5b36da5
07612e2
 
 
 
 
 
 
 
5b36da5
 
07612e2
 
 
5b36da5
07612e2
 
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
"""
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)