|
| 1 | +import httpx |
| 2 | +from typing import Any, Optional, Dict |
| 3 | + |
| 4 | + |
| 5 | +class APIErrorResponse: |
| 6 | + def __init__(self, message: str, status_code: int): |
| 7 | + self.message = message |
| 8 | + self.status_code = status_code |
| 9 | + |
| 10 | + def to_dict(self) -> Dict[str, Any]: |
| 11 | + return {"error": self.message, "status_code": self.status_code} |
| 12 | + |
| 13 | + def __repr__(self) -> str: |
| 14 | + return f"<APIErrorResponse(status_code={self.status_code}, message='{self.message}')>" |
| 15 | + |
| 16 | + |
| 17 | +class APIResponse: |
| 18 | + def __init__(self, response: httpx.Response): |
| 19 | + self._response = response |
| 20 | + self.status_code = response.status_code |
| 21 | + self.headers = response.headers |
| 22 | + self._json = self._parse_json(response) |
| 23 | + |
| 24 | + def _parse_json(self, response: httpx.Response) -> Optional[Any]: |
| 25 | + """Parses the JSON content of the response.""" |
| 26 | + try: |
| 27 | + return response.json() |
| 28 | + except ValueError: |
| 29 | + return APIErrorResponse("Invalid JSON response", response.status_code) |
| 30 | + |
| 31 | + @property |
| 32 | + def json(self) -> Optional[Any]: |
| 33 | + """Returns the JSON content of the response or an APIErrorResponse if parsing fails.""" |
| 34 | + return self._json |
| 35 | + |
| 36 | + def is_success(self) -> bool: |
| 37 | + """Returns True if the response status code indicates success.""" |
| 38 | + return 200 <= self.status_code < 300 |
| 39 | + |
| 40 | + def raise_for_status(self): |
| 41 | + """Raises an HTTPError if the response status code indicates an error.""" |
| 42 | + if not self.is_success(): |
| 43 | + raise httpx.HTTPStatusError( |
| 44 | + f"HTTP Error {self.status_code} for url {self._response.url}", |
| 45 | + request=self._response.request, |
| 46 | + response=self._response, |
| 47 | + ) |
| 48 | + |
| 49 | + def __repr__(self) -> str: |
| 50 | + return ( |
| 51 | + f"<APIResponse(status_code={self.status_code}, " |
| 52 | + f"headers={dict(self.headers)}, " |
| 53 | + f"json={self._json})>" |
| 54 | + ) |
0 commit comments