|
1 | | -"""HTTP API client layer for Agentic Exchange SDK.""" |
| 1 | +"""Resilient HTTP API client for the Agentic Exchange SDK.""" |
2 | 2 |
|
3 | | -from typing import Any, Dict, Optional |
| 3 | +import logging |
| 4 | +import time |
| 5 | +from typing import Any, Dict, Optional, Tuple, Type |
4 | 6 |
|
5 | 7 | import requests |
6 | 8 | from requests import Session |
7 | 9 |
|
8 | | -from .exceptions import AuthenticationError, NetworkError, RateLimitError, ValidationError |
9 | | -from .utils import exponential_backoff_retry, logger |
| 10 | +from .exceptions import ( |
| 11 | + AuthenticationError, |
| 12 | + NetworkError, |
| 13 | + RateLimitError, |
| 14 | + ResourceNotFoundError, |
| 15 | + ValidationError, |
| 16 | +) |
| 17 | +from .utils import exponential_backoff_retry |
| 18 | + |
| 19 | +# Configure default logger |
| 20 | +logger = logging.getLogger("agentic_exchange") |
10 | 21 |
|
11 | 22 |
|
12 | 23 | class ApiClient: |
13 | | - def __init__(self, api_key: str, base_url: str = "https://api.agentic.exchange", timeout: int = 15): |
14 | | - self.api_key = api_key |
15 | | - self.base_url = base_url.rstrip("/") |
16 | | - self.timeout = timeout |
17 | | - self.session: Session = requests.Session() |
18 | | - self.session.headers.update( |
19 | | - { |
20 | | - "Authorization": f"Bearer {self.api_key}", |
21 | | - "Content-Type": "application/json", |
22 | | - "Accept": "application/json", |
23 | | - } |
24 | | - ) |
25 | | - |
26 | | - def _url(self, path: str) -> str: |
27 | | - return f"{self.base_url}{path}" |
28 | | - |
29 | | - @exponential_backoff_retry( |
30 | | - retries=3, |
31 | | - initial_delay=0.5, |
32 | | - factor=2.0, |
33 | | - allowed_exceptions=(requests.RequestException,), |
34 | | - ) |
35 | | - def post(self, path: str, json: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: |
36 | | - url = self._url(path) |
37 | | - try: |
38 | | - resp = self.session.post(url, json=json, timeout=self.timeout) |
39 | | - except requests.RequestException as e: |
40 | | - logger.debug("Network error posting to %s: %s", url, e) |
41 | | - raise NetworkError("Network error", e) |
42 | | - return self._handle_response(resp) |
43 | | - |
44 | | - @exponential_backoff_retry( |
45 | | - retries=3, |
46 | | - initial_delay=0.5, |
47 | | - factor=2.0, |
48 | | - allowed_exceptions=(requests.RequestException,), |
49 | | - ) |
50 | | - def get(self, path: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: |
51 | | - url = self._url(path) |
52 | | - try: |
53 | | - resp = self.session.get(url, params=params, timeout=self.timeout) |
54 | | - except requests.RequestException as e: |
55 | | - logger.debug("Network error getting %s: %s", url, e) |
56 | | - raise NetworkError("Network error", e) |
57 | | - return self._handle_response(resp) |
58 | | - |
59 | | - def _handle_response(self, resp: requests.Response) -> Dict[str, Any]: |
60 | | - status = resp.status_code |
61 | | - try: |
62 | | - payload = resp.json() |
63 | | - except ValueError: |
64 | | - payload = {"message": resp.text} |
65 | | - |
66 | | - if status == 401: |
67 | | - raise AuthenticationError(payload.get("message", "Unauthorized")) |
68 | | - if status == 422: |
69 | | - raise ValidationError(payload.get("message", "Validation error")) |
70 | | - if status == 429: |
71 | | - raise RateLimitError(payload.get("message", "Rate limited")) |
72 | | - if status >= 400: |
73 | | - raise NetworkError(f"HTTP {status}: {payload}") |
74 | | - |
75 | | - return payload |
| 24 | + """Internal client handling HTTP communication, retries, and error mapping.""" |
| 25 | + |
| 26 | + def __init__( |
| 27 | + self, |
| 28 | + api_key: str, |
| 29 | + base_url: str = "http://127.0.0.1:8000", |
| 30 | + timeout: int = 30, |
| 31 | + debug: bool = False |
| 32 | + ): |
| 33 | + self.api_key = api_key |
| 34 | + self.base_url = base_url.rstrip("/") |
| 35 | + self.timeout = timeout |
| 36 | + self.debug = debug |
| 37 | + self.session: Session = requests.Session() |
| 38 | + |
| 39 | + self.session.headers.update({ |
| 40 | + "Authorization": f"Bearer {self.api_key}", |
| 41 | + "Content-Type": "application/json", |
| 42 | + "Accept": "application/json", |
| 43 | + "User-Agent": "AgenticExchange-PythonSDK/0.1.0" |
| 44 | + }) |
| 45 | + |
| 46 | + if self.debug: |
| 47 | + logger.setLevel(logging.DEBUG) |
| 48 | + |
| 49 | + def _url(self, path: str) -> str: |
| 50 | + # Ensure path starts with / |
| 51 | + if not path.startswith("/"): |
| 52 | + path = f"/{path}" |
| 53 | + return f"{self.base_url}{path}" |
| 54 | + |
| 55 | + @exponential_backoff_retry( |
| 56 | + retries=3, |
| 57 | + initial_delay=1.0, |
| 58 | + factor=2.0, |
| 59 | + allowed_exceptions=(requests.RequestException, NetworkError), |
| 60 | + ) |
| 61 | + def request( |
| 62 | + self, |
| 63 | + method: str, |
| 64 | + path: str, |
| 65 | + json: Optional[Dict[str, Any]] = None, |
| 66 | + params: Optional[Dict[str, Any]] = None |
| 67 | + ) -> Dict[str, Any]: |
| 68 | + """Perform an HTTP request with automatic retries and error handling.""" |
| 69 | + url = self._url(path) |
| 70 | + if self.debug: |
| 71 | + logger.debug(f"Request: {method} {url} | Params: {params} | Body: {json}") |
| 72 | + |
| 73 | + try: |
| 74 | + resp = self.session.request( |
| 75 | + method=method, |
| 76 | + url=url, |
| 77 | + json=json, |
| 78 | + params=params, |
| 79 | + timeout=self.timeout |
| 80 | + ) |
| 81 | + return self._handle_response(resp) |
| 82 | + except requests.Timeout as e: |
| 83 | + logger.error(f"Timeout connecting to {url}") |
| 84 | + raise NetworkError(f"Request timed out after {self.timeout}s", e) |
| 85 | + except requests.RequestException as e: |
| 86 | + logger.error(f"Network error: {e}") |
| 87 | + raise NetworkError("Failed to connect to Agentic Exchange API", e) |
| 88 | + |
| 89 | + def _handle_response(self, resp: requests.Response) -> Dict[str, Any]: |
| 90 | + """Maps HTTP status codes to custom SDK exceptions.""" |
| 91 | + status = resp.status_code |
| 92 | + |
| 93 | + try: |
| 94 | + payload = resp.json() |
| 95 | + except ValueError: |
| 96 | + payload = {"detail": resp.text} |
| 97 | + |
| 98 | + if self.debug: |
| 99 | + logger.debug(f"Response: {status} | Payload: {payload}") |
| 100 | + |
| 101 | + if 200 <= status < 300: |
| 102 | + return payload |
| 103 | + |
| 104 | + error_msg = payload.get("detail", payload.get("message", "An unexpected error occurred")) |
| 105 | + |
| 106 | + if status == 401: |
| 107 | + raise AuthenticationError(f"Authentication failed: {error_msg}", payload) |
| 108 | + if status == 404: |
| 109 | + raise ResourceNotFoundError(f"Resource not found: {error_msg}", payload) |
| 110 | + if status == 422: |
| 111 | + raise ValidationError(f"Invalid request parameters: {error_msg}", payload) |
| 112 | + if status == 429: |
| 113 | + raise RateLimitError(f"Rate limit exceeded: {error_msg}", payload) |
| 114 | + if status >= 500: |
| 115 | + raise NetworkError(f"Server error (HTTP {status}): {error_msg}") |
| 116 | + |
| 117 | + raise NetworkError(f"Unexpected HTTP {status}: {error_msg}", payload) |
| 118 | + |
| 119 | + def get(self, path: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: |
| 120 | + return self.request("GET", path, params=params) |
| 121 | + |
| 122 | + def post(self, path: str, json: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: |
| 123 | + return self.request("POST", path, json=json) |
| 124 | + |
| 125 | + def patch(self, path: str, json: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: |
| 126 | + return self.request("PATCH", path, json=json) |
0 commit comments