|
| 1 | +"""Low-level HTTP transport using urllib (stdlib only).""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json |
| 6 | +import urllib.error |
| 7 | +import urllib.parse |
| 8 | +import urllib.request |
| 9 | +from typing import Any, Optional |
| 10 | + |
| 11 | +from .exceptions import ( |
| 12 | + DelegaAPIError, |
| 13 | + DelegaAuthError, |
| 14 | + DelegaNotFoundError, |
| 15 | + DelegaRateLimitError, |
| 16 | +) |
| 17 | + |
| 18 | +_DEFAULT_TIMEOUT = 30 |
| 19 | + |
| 20 | + |
| 21 | +class HTTPClient: |
| 22 | + """Synchronous HTTP client using urllib.""" |
| 23 | + |
| 24 | + def __init__(self, base_url: str, api_key: str, timeout: int = _DEFAULT_TIMEOUT) -> None: |
| 25 | + self._base_url = base_url.rstrip("/") |
| 26 | + self._api_key = api_key |
| 27 | + self._timeout = timeout |
| 28 | + |
| 29 | + def _headers(self) -> dict[str, str]: |
| 30 | + return { |
| 31 | + "X-Agent-Key": self._api_key, |
| 32 | + "Content-Type": "application/json", |
| 33 | + "Accept": "application/json", |
| 34 | + } |
| 35 | + |
| 36 | + def request( |
| 37 | + self, |
| 38 | + method: str, |
| 39 | + path: str, |
| 40 | + *, |
| 41 | + params: Optional[dict[str, Any]] = None, |
| 42 | + body: Optional[dict[str, Any]] = None, |
| 43 | + ) -> Any: |
| 44 | + """Send an HTTP request and return the parsed JSON response. |
| 45 | +
|
| 46 | + Args: |
| 47 | + method: HTTP method (GET, POST, PUT, PATCH, DELETE). |
| 48 | + path: API path (e.g. ``/v1/tasks``). |
| 49 | + params: Optional query parameters. |
| 50 | + body: Optional JSON request body. |
| 51 | +
|
| 52 | + Returns: |
| 53 | + Parsed JSON response, or ``True`` for successful ``DELETE`` |
| 54 | + requests with no body. |
| 55 | +
|
| 56 | + Raises: |
| 57 | + DelegaAuthError: On 401/403 responses. |
| 58 | + DelegaNotFoundError: On 404 responses. |
| 59 | + DelegaRateLimitError: On 429 responses. |
| 60 | + DelegaAPIError: On other non-2xx responses. |
| 61 | + """ |
| 62 | + url = self._base_url + path |
| 63 | + if params: |
| 64 | + filtered = {k: v for k, v in params.items() if v is not None} |
| 65 | + if filtered: |
| 66 | + query = urllib.parse.urlencode(filtered, doseq=True) |
| 67 | + url = f"{url}?{query}" |
| 68 | + |
| 69 | + data = json.dumps(body).encode("utf-8") if body is not None else None |
| 70 | + req = urllib.request.Request(url, data=data, headers=self._headers(), method=method) |
| 71 | + |
| 72 | + try: |
| 73 | + with urllib.request.urlopen(req, timeout=self._timeout) as resp: |
| 74 | + resp_body = resp.read().decode("utf-8") |
| 75 | + if not resp_body: |
| 76 | + return True |
| 77 | + return json.loads(resp_body) |
| 78 | + except urllib.error.HTTPError as exc: |
| 79 | + error_body = exc.read().decode("utf-8", errors="replace") |
| 80 | + try: |
| 81 | + error_data = json.loads(error_body) |
| 82 | + message = error_data.get("error", error_data.get("message", error_body)) |
| 83 | + except (json.JSONDecodeError, ValueError): |
| 84 | + message = error_body or exc.reason |
| 85 | + |
| 86 | + status = exc.code |
| 87 | + if status in (401, 403): |
| 88 | + raise DelegaAuthError(error_message=message, status_code=status) from exc |
| 89 | + if status == 404: |
| 90 | + raise DelegaNotFoundError(error_message=message) from exc |
| 91 | + if status == 429: |
| 92 | + raise DelegaRateLimitError(error_message=message) from exc |
| 93 | + raise DelegaAPIError(status_code=status, error_message=message) from exc |
| 94 | + |
| 95 | + def get(self, path: str, *, params: Optional[dict[str, Any]] = None) -> Any: |
| 96 | + """Send a GET request.""" |
| 97 | + return self.request("GET", path, params=params) |
| 98 | + |
| 99 | + def post(self, path: str, *, body: Optional[dict[str, Any]] = None) -> Any: |
| 100 | + """Send a POST request.""" |
| 101 | + return self.request("POST", path, body=body) |
| 102 | + |
| 103 | + def patch(self, path: str, *, body: Optional[dict[str, Any]] = None) -> Any: |
| 104 | + """Send a PATCH request.""" |
| 105 | + return self.request("PATCH", path, body=body) |
| 106 | + |
| 107 | + def put(self, path: str, *, body: Optional[dict[str, Any]] = None) -> Any: |
| 108 | + """Send a PUT request.""" |
| 109 | + return self.request("PUT", path, body=body) |
| 110 | + |
| 111 | + def delete(self, path: str) -> Any: |
| 112 | + """Send a DELETE request.""" |
| 113 | + return self.request("DELETE", path) |
0 commit comments