Skip to content

Network

A small, dependency-free async HTTP client. Use fetch for the common "call a JSON API" path; reach for httpx / aiohttp if you need multipart, streaming, or HTTP/2.

Async HTTP client (pn.fetch).

A small, dependency-free coroutine wrapper around :mod:urllib.request. Operates on bytes internally and exposes a :class:Response with text(), json(), and bytes accessors.

The implementation is deliberately minimal — it covers the "call a JSON API" path that's overwhelmingly the use case for mobile apps. For streaming, multipart uploads, or HTTP/2, integrate httpx / aiohttp directly; this module won't try to compete.

Example
import pythonnative as pn


async def load_user(user_id):
    resp = await pn.fetch(
        f"https://api.example.com/users/{user_id}",
        headers={"Accept": "application/json"},
    )
    resp.raise_for_status()
    return resp.json()

Classes:

Name Description
Response

The result of a fetch call.

HTTPError

Functions:

Name Description
set_default_ssl_context

Override the SSL context used by fetch.

fetch

Make an HTTP request and return a Response.

Response dataclass

Response(status: int, url: str, headers: Mapping[str, str] = dict(), content: bytes = b'')

The result of a fetch call.

Attributes:

Name Type Description
status int

HTTP status code (e.g. 200).

url str

Final URL after any redirects.

headers Mapping[str, str]

Response headers, case-insensitive.

content bytes

Raw response body.

Methods:

Name Description
text

Decode content to str.

json

Parse the response body as JSON.

raise_for_status

Raise HTTPError for non-2xx responses.

ok property

ok: bool

True if the status is in the 2xx range.

text

text(encoding: Optional[str] = None) -> str

Decode content to str.

Parameters:

Name Type Description Default
encoding Optional[str]

Optional override; defaults to the charset parameter of Content-Type (or UTF-8).

None

json

json() -> Any

Parse the response body as JSON.

Raises:

Type Description
JSONDecodeError

If the body isn't valid JSON.

raise_for_status

raise_for_status() -> None

Raise HTTPError for non-2xx responses.

HTTPError

HTTPError(status: int, url: str, body: str)

set_default_ssl_context

set_default_ssl_context(context: Optional[SSLContext]) -> None

Override the SSL context used by fetch.

None (the default) means urllib builds a context from the system trust store. Tests can pass an unverified context.

fetch async

fetch(url: str, *, method: str = 'GET', headers: Optional[Mapping[str, str]] = None, body: Union[bytes, str, Mapping[str, Any], None] = None, params: Optional[Mapping[str, Any]] = None, timeout: float = 30.0) -> Response

Make an HTTP request and return a Response.

Parameters:

Name Type Description Default
url str

Target URL. Relative URLs are not supported.

required
method str

HTTP method ("GET", "POST", "PUT" …).

'GET'
headers Optional[Mapping[str, str]]

Optional request headers.

None
body Union[bytes, str, Mapping[str, Any], None]

Request body. bytes are sent as-is; str is UTF-8 encoded; dict is JSON-encoded with a Content-Type: application/json header added (unless already supplied).

None
params Optional[Mapping[str, Any]]

Optional mapping of query-string parameters appended to url (urlencoded).

None
timeout float

Seconds to wait for the response (excluding the time spent on DNS / connect).

30.0

Returns:

Type Description
Response

Raises:

Type Description
TimeoutError

If the request doesn't complete within timeout seconds.

OSError

For network errors (DNS failure, connection refused, etc.) — re-raised from urllib.

Example
resp = await pn.fetch(
    "https://api.example.com/posts",
    method="POST",
    body={"title": "Hello"},
)
resp.raise_for_status()

Patterns

  • Inside a component: pair with use_query for loading/error state and automatic cancellation on unmount.
  • In an event handler: wrap an async def in pn.run_async so a sync on_click can drive an awaitable request.
  • Mutations: pair with use_mutation to track loading / error for POST/PUT/DELETE flows.