This release is a pre-release and may not be stable for production use.
pyxpo-fetch
HTTP requests with streaming response bodies for pyxpo apps written in Python. It uses
the platform's own networking, so system proxies, certificates and cookies apply. The API follows
expo/fetch, which is the WinterCG fetch: iOS uses
URLSession and Android uses OkHttp.
from pyxpo_fetch import fetch
resp = await fetch("https://api.example.com/items")
if resp.ok:
items = await resp.json()
Features
- Familiar API:
fetch(url, method=, headers=, body=)returns aResponsewithstatus,ok,headers,text(),json(),bytes(). - Streaming:
async for chunk in resp.bodygives bytes as they arrive: server-sent events, LLM replies, big downloads. - Abort: an
AbortControllerstops a request, even while its body streams. - Timeouts, redirects, cookies:
timeout,redirect="follow" | "manual" | "error",credentials="include" | "omit". - Honest errors: HTTP 404 and 500 do not raise. Network failures raise
FetchError. - Case-insensitive
Headersthat joins repeated values as the web does. - HTTP client, axios style:
create_client(base_url=, headers=, timeout=, retry=)with request and response interceptors, parsed JSON inres.data,HTTPErroron error statuses, retries with backoff andRetry-After, queryparams, form bodies, download progress andextend()for derived clients. - Typed: ships
py.typed.
Contents
| If you are... | Start here |
|---|---|
| Calling a JSON API | Quick start |
| Sending JSON or bytes | Sending data |
| Streaming a response | Streaming |
| Cancelling or timing out | Abort and timeouts |
| Handling failures | Errors |
| Wanting interceptors, retries, a base URL | HTTP client |
| Exact signatures | API reference |
| Seeing it in a real app | Recipe: a search box |
| Stuck | Testing · Troubleshooting · FAQ |
Platform support
| Target | What works |
|---|---|
| Android, API 24+ | OkHttp 4.12. Adds the INTERNET permission. Cookies live in memory while the app runs. |
| iOS 15+ | URLSession. Cookies use the shared cookie store. |
| Desktop window | urllib in a worker thread, with an in-memory cookie jar. |
| Web page | The browser's own fetch, streamed with a ReadableStream reader. CORS applies: the server must allow your page's origin. redirect="manual" gives an opaque response, as in the browser. |
Requires Python 3.9+ and pyxpo>=0.1.0a1.
Install
pip install pyxpo-fetch
[tool.pyxpo]
modules = ["fetch"]
Rebuild the app. There are no plugin options. Plain http:// URLs need the server to be allowed by the app (pyxpo apps
allow local hosts), so prefer https://.
Quick start
from pyxpo import Button, Text, View, component, use_async, use_state
from pyxpo_fetch import FetchError, fetch
@component
def Hello():
taps, set_taps = use_state(0)
line, set_line = use_state("Press the button")
async def go():
if taps == 0:
return
try:
resp = await fetch("https://example.com/", timeout=10)
text = await resp.text()
set_line("%s %s, %d bytes" % (resp.status, resp.status_text, len(text)))
except FetchError as e:
set_line("Offline? %s" % e)
use_async(go, [taps])
return View(Text(line), Button("GET example.com", lambda: set_taps(taps + 1)))
Tip: Start a request from a button with a counter in state and
use_async(go, [counter]). Alambda: go()only builds a coroutine that nobody awaits.
The screenshot is from iOS. The Android emulator used for the screenshots had no internet access, so its request ended in
a FetchError, which is the behavior to expect on a phone in airplane mode.
Sending data
import json
resp = await fetch(
"https://api.example.com/items",
method="POST",
headers={"Content-Type": "application/json", "Authorization": "Bearer " + token},
body=json.dumps({"name": "pen"}),
)
bodyisstr(UTF-8,Content-Typedefaults totext/plain;charset=UTF-8) orbytes. Dicts are not accepted (usejson.dumps). GET and HEAD cannot have a body (ValueError).headersis a dict, a list of pairs, or aHeadersobject.methodis upper-cased for you.
Reading the response
| Member | Notes |
|---|---|
status, status_text, ok |
ok is true for 200 to 299. |
headers |
get(name), get_all(name), get_set_cookie(), has(name), keys(), items(), and name in headers. |
url, redirected |
The final URL, and whether a redirect led there. |
await text() / json() / bytes() / array_buffer() |
Read the whole body. |
body |
An async iterator of bytes chunks. |
body_used |
A body can be read only once. A second read raises RuntimeError. |
Streaming
resp = await fetch("https://example.com/events")
async for chunk in resp.body:
handle(chunk) # bytes, as they arrive
Stop early with await resp.body.cancel(). On iOS URLSession holds back the first 512 bytes of a body for MIME
sniffing, so a streaming server should send X-Content-Type-Options: nosniff or a type such as text/event-stream, or
the first chunks arrive late.
Abort and timeouts
import asyncio
from pyxpo_fetch import AbortController, AbortError
ctl = AbortController()
task = asyncio.ensure_future(fetch(url, signal=ctl.signal)) # pass the signal
...
ctl.abort() # the awaiting call raises AbortError
An already aborted signal raises AbortError before the request starts. timeout= is in seconds. redirect="manual"
returns the 3xx response itself; "error" raises FetchError. credentials="omit" sends and stores no cookies.
Errors
| Error | When | What to do |
|---|---|---|
FetchError |
No connection, DNS, TLS, timeout, refused redirect, or a body that breaks off. | Show a retry. Do not assume the server saw the request. |
AbortError (a FetchError) |
The signal was aborted. | Usually nothing: the user or your code cancelled. |
ValueError |
Bad redirect or credentials, a non-http(s) URL, or a body on GET or HEAD. |
Fix the call. |
TypeError |
body is not str or bytes. |
Use json.dumps(...). |
RuntimeError |
The body was read twice. | Read it once and keep the result. |
ModuleNotLinkedError (from pyxpo.module_api) |
Built without "fetch" in modules. |
Add it and rebuild. |
resp.ok is False |
The server answered 4xx or 5xx. This is not an exception. | Check resp.status, and read the body for the reason. |
Config
None.
Web and desktop
On the desktop window requests use urllib on a worker thread, with an in-memory cookie jar, so the UI stays smooth. The
web page calls the browser's fetch: cookies follow the browser's rules, and a server on another origin must send
CORS headers for your page (and allow any custom headers you send). A CORS refusal raises FetchError.
HTTP client
fetch stays close to the web. For an app talking to one API, create_client adds what axios gives you: shared
defaults, interceptors, parsed bodies, errors for error statuses, retries and a timeout per request.
from pyxpo_fetch import HTTPError, Retry, TimeoutError, create_client
api = create_client(
base_url="https://api.example.com/v1",
headers={"Accept": "application/json"},
timeout=15, # seconds, per attempt
retry=Retry(2, backoff=0.3), # GET/PUT/DELETE on network errors, timeouts, 408/429/502/503/504
)
@api.interceptors.request.use
def sign(config):
config.headers.set("Authorization", "Bearer " + session.token)
async def refresh_once(error):
if isinstance(error, HTTPError) and error.status == 401 and not error.config.meta.get("refreshed"):
await session.refresh()
error.config.meta["refreshed"] = True
return await api.request(error.config) # runs the interceptors again, so it carries the new token
raise error
api.interceptors.response.use(None, refresh_once)
res = await api.get("/posts", params={"page": 2, "draft": False, "tag": ["a", "b"]})
res.data # parsed JSON (text when the body is not JSON)
res.status, res.headers, res.config
await api.post("/posts", {"title": "Hello"}) # JSON body, Content-Type set for you
await api.post("/login", form={"user": "ana"}) # form body
await api.get("/export", response_type="bytes", on_download_progress=lambda got, total: print(got, total))
- Interceptors run in the order you add them and may be
async. A request interceptor gets theRequestConfig; returning None keeps it. A response interceptor gets theClientResponse. Its error side gets the exception: return a response to recover, or raise.use()works as a decorator;add()returns an id;eject(id_or_function). - Errors: an error status raises
HTTPErrorwith.status,.data,.responseand.config. Passraise_for_status=False(or a function of the status) to get the response instead. Running pasttimeoutraisesTimeoutError; your ownsignalraisesAbortError; no network raisesFetchError. All three areFetchErrors. response_type:"auto"(JSON when it looks like JSON),"json","text","bytes"or"stream"(res.datais then the body's async iterator).config.metais a free dict for your own flags, such as "already retried".api.extend(headers=..., timeout=...)makes a new client with merged defaults and a copy of the interceptors.transport=swaps the function that sends the request. Tests pass a fake with thefetchsignature.gather_settled(*calls)runs requests together and returns each response or error.
Recipe: a search box
Look up what the user types in a JSON API, with a timeout and clear messages when it fails.
from urllib.parse import quote
from pyxpo import Text, TextInput, View, component, use_async, use_state
from pyxpo_fetch import FetchError, fetch
@component
def Search():
q, set_q = use_state("")
result, set_result = use_state("")
async def look_up():
if len(q) < 2:
set_result("")
return
try:
resp = await fetch("https://api.example.com/search?q=" + quote(q), timeout=8)
if not resp.ok:
set_result("Server said %d" % resp.status)
return
data = await resp.json()
set_result(", ".join(item["name"] for item in data.get("items", [])))
except FetchError as e:
set_result("Could not search: %s" % e)
use_async(look_up, [q])
return View(TextInput(value=q, on_change_text=set_q, placeholder="Search"), Text(result))
Production checklist
- Every call is inside
try/except FetchErrorand shows a retry. - You check
resp.okbefore using the body. - You set a
timeout. - You use
https://, and secrets are in headers (frompyxpo-secure-store), not in URLs. - Streaming servers send
nosniffor an event-stream type so iOS delivers chunks at once. - You tested in airplane mode.
- For the web build, the API allows your site's origin and custom headers (CORS).
Testing
The module is easy to fake. Fakes can replace fetch in your own module, or replace the native bridge:
import asyncio
import pytest
import pyxpo_fetch as mod
from pyxpo_fetch import Headers
def test_headers_case_insensitive():
h = Headers({"Content-Type": "text/plain"})
h.append("Set-Cookie", "a=1")
h.append("set-cookie", "b=2")
assert h.get("content-type") == "text/plain"
assert h.get_set_cookie() == ["a=1", "b=2"]
def test_error_status_does_not_raise(monkeypatch):
class Fake:
status, ok = 404, False
async def text(self):
return "nope"
async def fake_fetch(url, **kw):
return Fake()
monkeypatch.setattr(mod, "fetch", fake_fetch)
resp = asyncio.run(mod.fetch("https://x.test/"))
assert not resp.ok
def test_validation():
with pytest.raises(ValueError):
asyncio.run(mod.fetch("ftp://x.test/"))
with pytest.raises(ValueError):
asyncio.run(mod.fetch("https://x.test/", method="GET", body="x"))
Troubleshooting
| Symptom | Cause and fix |
|---|---|
FetchError on the Android emulator |
The emulator has no internet. Check its network, or test on a phone. |
ValueError: fetch needs an http(s) URL |
Add the scheme. |
Plain http:// fails on a device |
Use https://, or a local host allowed by the app. |
| Streaming chunks arrive late on iOS | Add X-Content-Type-Options: nosniff or Content-Type: text/event-stream on the server. |
RuntimeError: already read |
A body can be read once. Store the text. |
Works on a phone, FetchError in the browser |
CORS: the server does not allow your page's origin or one of your headers. Check the browser console. |
ModuleNotLinkedError |
Add "fetch" to modules and rebuild. |
FAQ
Does a 404 raise? No. Check resp.ok or resp.status.
Are cookies kept? Yes with credentials="include" (the default): the shared store on iOS, memory on Android and
desktop. Use "omit" to turn them off.
Can I upload a file? Send its bytes as body.
Is there fetch on the web page? Yes, the browser's own, with the same API.
API reference
fetch(url, *, method="GET", headers=None, body=None, redirect="follow", credentials="include", signal=None, timeout=None)
Returns a Response once the headers arrive.
| Argument | Notes |
|---|---|
url |
http:// or https://. |
redirect |
"follow", "manual", "error". |
credentials |
"include", "omit", "same-origin" (acts like include). |
signal |
AbortController().signal. |
timeout |
Seconds. |
Classes
| Name | Description |
|---|---|
Response |
status, status_text, ok, headers, url, redirected, body, body_used, text(), json(), bytes(), array_buffer(). camelCase aliases work (statusText, bodyUsed, arrayBuffer). |
Headers |
append, set, delete, get, get_all, get_set_cookie, has, keys, items. |
AbortController |
signal, abort(reason=None). |
AbortSignal |
aborted, reason, throw_if_aborted(). |
FetchError, AbortError |
Network failure, and cancellation (a FetchError). |
create_client(**defaults) / Client |
base_url, headers, params, timeout, retry, raise_for_status, response_type, redirect, credentials, transport. Methods request, get, head, options, delete, post, put, patch, extend, build, and interceptors.request / interceptors.response. |
RequestConfig |
method, url, base_url, params, headers, json, data, form, timeout, signal, response_type, retry, raise_for_status, on_download_progress, meta, attempt, full_url(). |
ClientResponse |
data, status, status_text, ok, headers, url, config, raw, json(). |
Retry(attempts=2, *, statuses, methods, backoff, max_backoff, on_timeout, when) |
Retry policy; Retry-After wins over backoff. |
HTTPError, TimeoutError |
Error status (with .response, .status, .data, .config), and a timeout. Both FetchErrors. |
License
MIT
Metadata
Release files for pyxpo-fetch 0.1.0a2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pyxpo_fetch-0.1.0a2.tar.gz | 37.8 kB | With provenance | Details for pyxpo_fetch-0.1.0a2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pyxpo_fetch-0.1.0a2-py3-none-any.whl | Python 3 | none | any | Details for pyxpo_fetch-0.1.0a2-py3-none-any.whl |
Total release size: 64.9 kB
Release files / pyxpo_fetch-0.1.0a2.tar.gz
| Download URL | pyxpo_fetch-0.1.0a2.tar.gz |
|---|---|
| Size | 37.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
49f696cc4cdbdfd54506d7edd39c7d573d5d2712fd68c3b5de8b27995e5c1781
|
|
BLAKE2b-256 checksum How to use checksums |
7c9866916a9398b9b66de062a61875166eb47880116951006f45ff7666d2fe53
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 30, 2026.
Transparency logRelease files / pyxpo_fetch-0.1.0a2-py3-none-any.whl
| Download URL | pyxpo_fetch-0.1.0a2-py3-none-any.whl |
|---|---|
| Size | 27.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
baa6646e51da6d0838b6c5db52ab6a700fc522f243d2ade17dad6872a033f19e
|
|
BLAKE2b-256 checksum How to use checksums |
331e755eee4d5188d4823d13fd5427e3a85e7a2ad366b8e8f6e0b5242a51a676
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 30, 2026.
Transparency logSecurity for pyxpo-fetch 0.1.0a2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for pyxpo_fetch-0.1.0a2.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 30, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.