Skip to content

httpx

httpx has the same json= and raise_for_status() as requests, and adds an async client.

Sync

import logging

import httpx

from jsonrpcclient import Error, Ok, parse, request

response = httpx.post("http://localhost:8000/", json=request("ping"), timeout=10)
response.raise_for_status()
parsed = parse(response.json())
if isinstance(parsed, Ok):
    print(parsed.result)
elif isinstance(parsed, Error):
    logging.error(parsed.message)

Async

import asyncio
import logging

import httpx

from jsonrpcclient import Error, Ok, parse, request


async def main() -> None:
    async with httpx.AsyncClient(timeout=10) as client:
        response = await client.post("http://localhost:8000/", json=request("ping"))
    response.raise_for_status()
    parsed = parse(response.json())
    if isinstance(parsed, Ok):
        print(parsed.result)
    elif isinstance(parsed, Error):
        logging.error(parsed.message)


asyncio.run(main())

raise_for_status() raises httpx.HTTPStatusError for a 4xx or 5xx status. Connection problems and timeouts raise subclasses of httpx.TransportError. For many calls, keep one httpx.Client or httpx.AsyncClient open and reuse it.