-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_client.py
More file actions
261 lines (216 loc) · 8.73 KB
/
Copy pathapi_client.py
File metadata and controls
261 lines (216 loc) · 8.73 KB
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
"""
API Client module for MultiAPI Dashboard.
Provides a centralized HTTP client with automatic retries,
exponential backoff, response caching, timeout handling,
and user-friendly error messages.
"""
import time
from typing import Any, Dict, Optional, Tuple
import requests
from requests.exceptions import (
ConnectionError,
HTTPError,
JSONDecodeError,
ReadTimeout,
RequestException,
)
from config import (
CACHE_TTL,
MAX_RETRIES,
REQUEST_TIMEOUT,
RETRY_BACKOFF,
USER_AGENT,
)
from logger import logger
class APIClient:
"""
Centralized HTTP client for all API interactions.
Features:
- Session-based connection pooling
- Automatic retry with exponential backoff
- In-memory response caching with TTL
- Unified error handling
- Request logging
"""
def __init__(self) -> None:
"""Initialize the API client with a requests session."""
self._session = requests.Session()
self._session.headers.update({
"User-Agent": USER_AGENT,
"Accept": "application/json",
})
self._cache: Dict[str, Tuple[float, Any]] = {}
def get(
self,
url: str,
params: Optional[Dict[str, str]] = None,
use_cache: bool = True,
timeout: int = REQUEST_TIMEOUT,
) -> Dict[str, Any]:
"""
Make a GET request with retry logic and caching.
Args:
url: The URL to request.
params: Optional query parameters.
use_cache: Whether to use cached responses.
timeout: Request timeout in seconds.
Returns:
Parsed JSON response as dictionary.
Raises:
APIError: On unrecoverable request failure.
"""
cache_key = self._build_cache_key(url, params)
# ── Check Cache ──────────────────────────────────────
if use_cache:
cached = self._get_cached(cache_key)
if cached is not None:
logger.debug(f"Cache hit for: {cache_key}")
return cached
# ── Make Request with Retries ────────────────────────
last_error: Optional[Exception] = None
for attempt in range(1, MAX_RETRIES + 1):
try:
logger.info(
f"API Request [Attempt {attempt}/{MAX_RETRIES}]: "
f"GET {url} | Params: {params}"
)
response = self._session.get(
url, params=params, timeout=timeout
)
response.raise_for_status()
data = response.json()
# Cache the successful response
if use_cache:
self._set_cache(cache_key, data)
logger.info(f"API Response: {response.status_code} OK")
return data
except ReadTimeout:
last_error = ReadTimeout(f"Request timed out after {timeout}s")
logger.warning(
f"Timeout on attempt {attempt}/{MAX_RETRIES}: {url}"
)
except ConnectionError:
last_error = ConnectionError("No internet connection")
logger.warning(
f"Connection error on attempt {attempt}/{MAX_RETRIES}: {url}"
)
except HTTPError as e:
status_code = e.response.status_code if e.response else 0
logger.error(f"HTTP {status_code} error: {url}")
# Don't retry on client errors (4xx) except 429
if e.response is not None and 400 <= status_code < 500 and status_code != 429:
raise APIError(
self._get_http_error_message(status_code),
status_code=status_code,
) from e
last_error = e
except JSONDecodeError:
last_error = JSONDecodeError("", "", 0)
logger.error(f"JSON parse error for: {url}")
except RequestException as e:
last_error = e
logger.error(f"Request error: {e}")
# Wait before retry (exponential backoff)
if attempt < MAX_RETRIES:
wait_time = RETRY_BACKOFF ** attempt
logger.info(f"Retrying in {wait_time:.1f}s...")
time.sleep(wait_time)
# All retries exhausted
error_msg = self._get_friendly_error(last_error)
logger.error(f"All retries exhausted for: {url} | Error: {error_msg}")
raise APIError(error_msg)
def get_text(
self,
url: str,
params: Optional[Dict[str, str]] = None,
timeout: int = REQUEST_TIMEOUT,
) -> str:
"""
Make a GET request and return raw text (for RSS/XML).
Args:
url: The URL to request.
params: Optional query parameters.
timeout: Request timeout in seconds.
Returns:
Raw response text.
Raises:
APIError: On request failure.
"""
try:
logger.info(f"API Text Request: GET {url}")
response = self._session.get(url, params=params, timeout=timeout)
response.raise_for_status()
logger.info(f"API Text Response: {response.status_code} OK")
return response.text
except Exception as e:
error_msg = self._get_friendly_error(e)
logger.error(f"Text request failed: {url} | Error: {error_msg}")
raise APIError(error_msg) from e
# ── Cache Management ─────────────────────────────────────
def _build_cache_key(
self, url: str, params: Optional[Dict[str, str]]
) -> str:
"""Build a unique cache key from URL and parameters."""
param_str = "&".join(
f"{k}={v}" for k, v in sorted((params or {}).items())
)
return f"{url}?{param_str}" if param_str else url
def _get_cached(self, key: str) -> Optional[Any]:
"""Retrieve a cached response if not expired."""
if key in self._cache:
timestamp, data = self._cache[key]
if time.time() - timestamp < CACHE_TTL:
return data
# Expired — remove it
del self._cache[key]
return None
def _set_cache(self, key: str, data: Any) -> None:
"""Store a response in the cache."""
self._cache[key] = (time.time(), data)
def clear_cache(self) -> None:
"""Clear all cached responses."""
self._cache.clear()
logger.info("API cache cleared")
# ── Error Message Helpers ────────────────────────────────
@staticmethod
def _get_http_error_message(status_code: int) -> str:
"""Map HTTP status codes to user-friendly messages."""
messages = {
400: "Bad request. Please check your input.",
401: "Authentication failed. Check your API key.",
403: "Access denied. API key may be invalid.",
404: "Not found. Please check your search term.",
429: "Too many requests. Please wait a moment.",
500: "Server error. The service is having issues.",
502: "Bad gateway. The service is temporarily down.",
503: "Service unavailable. Try again later.",
}
return messages.get(
status_code,
f"Unexpected HTTP error (status {status_code}).",
)
@staticmethod
def _get_friendly_error(error: Optional[Exception]) -> str:
"""Convert exceptions to user-friendly error messages."""
if error is None:
return "An unknown error occurred."
if isinstance(error, ConnectionError):
return "No internet connection. Please check your network."
if isinstance(error, ReadTimeout):
return "Request timed out. The server is not responding."
if isinstance(error, JSONDecodeError):
return "Unexpected response format from the server."
if isinstance(error, HTTPError):
return "The API service returned an error."
return f"An unexpected error occurred: {type(error).__name__}"
class APIError(Exception):
"""
Custom exception for API-related errors.
Attributes:
message: User-friendly error description.
status_code: HTTP status code (if applicable).
"""
def __init__(self, message: str, status_code: int = 0) -> None:
self.message = message
self.status_code = status_code
super().__init__(message)