Fetch a resource from the network using a Pythonic interface. This wraps JavaScript's fetch API, returning Python-native data types and supporting both direct promise awaiting and method chaining. The function takes a `url` and optional fetch `options` as keyword arguments. Th
(url, **options)
| 148 | |
| 149 | |
| 150 | def fetch(url, **options): |
| 151 | """ |
| 152 | Fetch a resource from the network using a Pythonic interface. |
| 153 | |
| 154 | This wraps JavaScript's fetch API, returning Python-native data types |
| 155 | and supporting both direct promise awaiting and method chaining. |
| 156 | |
| 157 | The function takes a `url` and optional fetch `options` as keyword |
| 158 | arguments. The `options` correspond to the JavaScript fetch API's |
| 159 | [RequestInit dictionary](https://developer.mozilla.org/en-US/docs/Web/API/RequestInit), |
| 160 | and commonly include: |
| 161 | |
| 162 | - `method`: HTTP method (e.g., `"GET"`, `"POST"`, `"PUT"` etc.) |
| 163 | - `headers`: Dict of request headers. |
| 164 | - `body`: Request body (string, dict for JSON, etc.) |
| 165 | |
| 166 | The function returns a promise that resolves to a Response-like object |
| 167 | with Pythonic methods to extract data: |
| 168 | |
| 169 | - `await response.json()` to get JSON as Python objects. |
| 170 | - `await response.text()` to get text data. |
| 171 | - `await response.bytearray()` to get raw data as a bytearray. |
| 172 | - `await response.arrayBuffer()` to get raw data as a memoryview or bytes. |
| 173 | - `await response.blob()` to get the raw JS Blob object. |
| 174 | |
| 175 | It's also possible to chain these methods directly on the fetch promise: |
| 176 | `data = await fetch(url).json()` |
| 177 | |
| 178 | The returned response object also exposes standard properties like |
| 179 | `ok`, `status`, and `statusText` for checking response status. |
| 180 | |
| 181 | ```python |
| 182 | # Simple GET request. |
| 183 | response = await fetch("https://api.example.com/data") |
| 184 | data = await response.json() |
| 185 | |
| 186 | # Method chaining. |
| 187 | data = await fetch("https://api.example.com/data").json() |
| 188 | |
| 189 | # POST request with JSON. |
| 190 | response = await fetch( |
| 191 | "https://api.example.com/users", |
| 192 | method="POST", |
| 193 | headers={"Content-Type": "application/json"}, |
| 194 | body=json.dumps({"name": "Alice"}) |
| 195 | ) |
| 196 | result = await response.json() |
| 197 | |
| 198 | # Check response status codes. |
| 199 | response = await fetch("https://api.example.com/data") |
| 200 | if response.ok: |
| 201 | # Status in the range 200-299. |
| 202 | data = await response.json() |
| 203 | elif response.status == 404: |
| 204 | print("Resource not found") |
| 205 | else: |
| 206 | print(f"Error: {response.status} {response.statusText}") |
| 207 | ``` |