Represents an HTTP response from an API request. Attributes: status: HTTP status code. status_text: HTTP status text. headers: Response headers as a dict. url: The request URL.
| 48 | |
| 49 | |
| 50 | class APIResponse: |
| 51 | """Represents an HTTP response from an API request. |
| 52 | |
| 53 | Attributes: |
| 54 | status: HTTP status code. |
| 55 | status_text: HTTP status text. |
| 56 | headers: Response headers as a dict. |
| 57 | url: The request URL. |
| 58 | """ |
| 59 | |
| 60 | def __init__(self, status: int, status_text: str, headers: dict[str, str], url: str, body: bytes) -> None: |
| 61 | self.status = status |
| 62 | self.status_text = status_text |
| 63 | self.headers = headers |
| 64 | self.url = url |
| 65 | self._body = body |
| 66 | |
| 67 | @property |
| 68 | def ok(self) -> bool: |
| 69 | """Whether the response status is in the 200-299 range.""" |
| 70 | return 200 <= self.status <= 299 |
| 71 | |
| 72 | def json(self) -> Any: |
| 73 | """Parse the response body as JSON. |
| 74 | |
| 75 | Returns: |
| 76 | The parsed JSON object. |
| 77 | """ |
| 78 | return json.loads(self._body) |
| 79 | |
| 80 | def text(self) -> str: |
| 81 | """Decode the response body as UTF-8 text. |
| 82 | |
| 83 | Returns: |
| 84 | The response body as a string. |
| 85 | """ |
| 86 | return self._body.decode("utf-8") |
| 87 | |
| 88 | def body(self) -> bytes: |
| 89 | """Return the raw response body bytes. |
| 90 | |
| 91 | Returns: |
| 92 | The response body as bytes. |
| 93 | """ |
| 94 | return self._body |
| 95 | |
| 96 | def dispose(self) -> None: |
| 97 | """Free the response body memory.""" |
| 98 | self._body = b"" |
| 99 | |
| 100 | |
| 101 | def _cookie_matches(cookie: dict, url: str, default_domain: str = "") -> bool: |
no outgoing calls