| [ Web Proxy ] |
| Viewing: https://pyodide.org/en/stable/usage/api/python-api/../python-api/http.html | [Back] [Original] |
The pyodide.http module provides HTTP client functionality specifically designed for browser and WebAssembly environments where traditional Python HTTP libraries (like urllib) face significant limitations.
Due to browser security constraints and WebAssemblys sandboxed environment, standard Python networking libraries have several limitations:
No raw socket access: Browser security prevents direct socket operations
CORS restrictions: Cross-origin requests are limited by browser CORS policies
No synchronous networking in main thread: Traditional blocking HTTP calls can freeze the browser UI
Limited protocol support: Only HTTP/HTTPS protocols are available, no TCP/UDP sockets
Pyodide provides two complementary HTTP client solutions:
pyfetch - Asynchronous HTTP Client#Based on the browsers native Fetch API, pyfetch provides:
Asynchronous operations: Non-blocking HTTP requests using async/await
Full browser integration: Leverages browsers networking stack and security features
Modern API: Clean, Promise-based interface similar to JavaScript fetch()
# Asynchronous HTTP request
from pyodide.http import pyfetch
response = await pyfetch("https://api.example.com/data")
data = await response.json()
pyxhr - Synchronous HTTP Client#Based on XMLHttpRequest, pyxhr provides:
Synchronous operations: Blocking HTTP requests for simpler code patterns
requests-like API: Familiar interface for Python developers
Browser compatibility: Works in all modern browsers supporting XMLHttpRequest
Lightweight: Minimal overhead for simple HTTP operations
# Synchronous HTTP request
from pyodide.http import pyxhr
response = pyxhr.get("https://api.example.com/data")
data = response.json()
Use pyfetch when:
Working with async/await patterns
Need advanced features like streaming or request cancellation
Building responsive web applications that shouldnt block the UI
Integrating with other asynchronous Python code
Use pyxhr when:
Prefer synchronous, blocking operations
Porting existing code that uses requests-like patterns
Need simple HTTP operations without async complexity
Working in environments where sync operations are acceptable
Exceptions:
|
|
|
|
|
A subclass of |
Classes:
|
A wrapper for a Javascript fetch |
Functions:
|
Fetches a given URL synchronously. |
|
Fetch the url and return the response. |
reason (JsException)
A wrapper for a Javascript fetch Response.
url URL that was fetched
js_response (JsFetchResponse) A JsProxy of the fetch Response.
abort_controller (Optional[AbortController]) The abort controller that may be used to cancel the fetch request.
abort_signal (Optional[AbortSignal]) The abort signal that was used for the fetch request.
Abort the fetch request.
In case abort_controller is not set, a ValueError is raised.
Has the response been used yet?
If so, attempting to retrieve the body again will raise an
OSError. Use clone() first to avoid this.
See Response.bodyUsed.
Return the response body as a Javascript ArrayBuffer.
Return an identical copy of the FetchResponse.
This method exists to allow multiple uses of FetchResponse
objects. See Response.clone().
Treat the response body as a JSON string and use
json.loads() to parse it into a Python object.
Any keyword arguments are passed to json.loads().
Return the response body as a memoryview object
Was the request successful?
See Response.ok.
Raise an HttpStatusError if the status of the response is an error (4xx or 5xx)
Was the request redirected?
See Response.redirected.
Response status code
See Response.status.
Response status text
See Response.statusText.
Return the response body as a string
Does the same thing as FetchResponse.text().
Deprecated since version 0.24.0: Use FetchResponse.text() instead.
The type of the response.
See Response.type.
Treat the data as an archive and unpack it into target directory.
Assumes that the file is an archive in a format that shutil has
an unpacker for. The arguments extract_dir and format are passed
directly on to shutil.unpack_archive().
extract_dir (Optional[str]) Directory to extract the archive into. If not provided, the current
working directory is used.
format (Optional[str]) The archive format: one of "zip", "tar", "gztar",
"bztar". Or any other format registered with
shutil.register_unpack_format(). If not provided,
unpack_archive() will use the archive file name extension and
see if an unpacker was registered for that extension. In case none
is found, a ValueError is raised.
The url of the response.
The value may be different than the url passed to fetch.
See Response.url.
A subclass of OSError raised by FetchResponse.raise_for_status()
if the response status is 4XX or 5XX.
Fetches a given URL synchronously.
The download of binary files is not supported. To download binary files use
pyodide.http.pyfetch() which is asynchronous.
It will not work in Node unless you include a polyfill for XMLHttpRequest
Examples
>>> None
>>> import pytest; pytest.skip("TODO: Figure out how to skip this only in node")
>>> url = "https://cdn.jsdelivr.net/pyodide/v0.24.1/full/pyodide-lock.json"
>>> url_contents = open_url(url)
>>> import json
>>> result = json.load(url_contents)
>>> sorted(list(result["info"].items()))
[('arch', 'wasm32'), ('platform', 'emscripten_3_1_45'), ('python', '3.11.3'), ('version', '0.24.1')]
Fetch the url and return the response.
This functions provides a similar API to fetch() however it is
designed to be convenient to use from Python. The
FetchResponse has methods with the output types
already converted to Python objects.
Examples
>>> import pytest; pytest.skip("Can't use top level await in doctests")
>>> res = await pyfetch("https://cdn.jsdelivr.net/pyodide/v0.23.4/full/repodata.json")
>>> res.ok
True
>>> res.status
200
>>> data = await res.json()
>>> data
{'info': {'arch': 'wasm32', 'platform': 'emscripten_3_1_32',
'version': '0.23.4', 'python': '3.11.2'}, ... # long output truncated
| Web Proxy Viewer | New URL | Original Page |