Skip to content

pyscript.fetch

This module provides a Python-friendly interface to the browser's fetch API, returning native Python data types and supporting directly awaiting the promise and chaining method calls directly on the promise.

from pyscript.fetch import fetch
url = "https://api.example.com/data"

# Pattern 1: Await the response, then extract data.
response = await fetch(url)
if response.ok:
    data = await response.json()
else:
    raise NetworkError(f"Fetch failed: {response.status}")

# Pattern 2: Chain method calls directly on the promise.
data = await fetch(url).json()

fetch(url, **options)

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. The options correspond to the JavaScript fetch API's RequestInit dictionary, and commonly include:

  • method: HTTP method (e.g., "GET", "POST", "PUT" etc.)
  • headers: Dict of request headers.
  • body: Request body (string, dict for JSON, etc.)

The function returns a promise that resolves to a Response-like object with Pythonic methods to extract data:

  • await response.json() to get JSON as Python objects.
  • await response.text() to get text data.
  • await response.bytearray() to get raw data as a bytearray.
  • await response.arrayBuffer() to get raw data as a memoryview or bytes.
  • await response.blob() to get the raw JS Blob object.

It's also possible to chain these methods directly on the fetch promise: data = await fetch(url).json()

The returned response object also exposes standard properties like ok, status, and statusText for checking response status.

# Simple GET request.
response = await fetch("https://api.example.com/data")
data = await response.json()

# Method chaining.
data = await fetch("https://api.example.com/data").json()

# POST request with JSON.
response = await fetch(
    "https://api.example.com/users",
    method="POST",
    headers={"Content-Type": "application/json"},
    body=json.dumps({"name": "Alice"})
)
result = await response.json()

# Check response status codes.
response = await fetch("https://api.example.com/data")
if response.ok:
    # Status in the range 200-299.
    data = await response.json()
elif response.status == 404:
    print("Resource not found")
else:
    print(f"Error: {response.status} {response.statusText}")
Source code in pyscript/fetch.py
def fetch(url, **options):
    """
    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. The `options` correspond to the JavaScript fetch API's
    [RequestInit dictionary](https://developer.mozilla.org/en-US/docs/Web/API/RequestInit),
    and commonly include:

    - `method`: HTTP method (e.g., `"GET"`, `"POST"`, `"PUT"` etc.)
    - `headers`: Dict of request headers.
    - `body`: Request body (string, dict for JSON, etc.)

    The function returns a promise that resolves to a Response-like object
    with Pythonic methods to extract data:

    - `await response.json()` to get JSON as Python objects.
    - `await response.text()` to get text data.
    - `await response.bytearray()` to get raw data as a bytearray.
    - `await response.arrayBuffer()` to get raw data as a memoryview or bytes.
    - `await response.blob()` to get the raw JS Blob object.

    It's also possible to chain these methods directly on the fetch promise:
    `data = await fetch(url).json()`

    The returned response object also exposes standard properties like
    `ok`, `status`, and `statusText` for checking response status.

    ```python
    # Simple GET request.
    response = await fetch("https://api.example.com/data")
    data = await response.json()

    # Method chaining.
    data = await fetch("https://api.example.com/data").json()

    # POST request with JSON.
    response = await fetch(
        "https://api.example.com/users",
        method="POST",
        headers={"Content-Type": "application/json"},
        body=json.dumps({"name": "Alice"})
    )
    result = await response.json()

    # Check response status codes.
    response = await fetch("https://api.example.com/data")
    if response.ok:
        # Status in the range 200-299.
        data = await response.json()
    elif response.status == 404:
        print("Resource not found")
    else:
        print(f"Error: {response.status} {response.statusText}")
    ```
    """
    # Convert Python dict to JavaScript object.
    js_options = js.JSON.parse(json.dumps(options))

    # Setup response handler to wrap the result.
    def on_response(response, *_):
        return _FetchPromise.setup(promise, response)

    promise = js.fetch(url, js_options).then(on_response)
    _FetchPromise(promise)
    return promise