Skip to content

aiohttp

from aiohttp import web

from jsonrpcserver import Result, Success, async_dispatch, method


@method
async def ping() -> Result:
    return Success("pong")


async def handle(request: web.Request) -> web.Response:
    # max_batch_size: see the Security page.
    if response := await async_dispatch(await request.text(), max_batch_size=100):
        return web.Response(text=response, content_type="application/json")
    return web.Response(status=204)


# Bigger requests get 413 Request Entity Too Large. The default is 1 MiB.
app = web.Application(client_max_size=1_000_000)
app.router.add_post("/", handle)

if __name__ == "__main__":
    web.run_app(app, host="localhost", port=8000)

aiohttp refuses a body bigger than client_max_size with 413. Its default is 1 MiB (1,048,576 bytes). The example sets 1,000,000, like the other examples. max_batch_size limits how many requests one batch can hold. See Security.

To give methods the request, pass it as context: await async_dispatch(..., context=request). See Context.

Try it

Save the example as aiohttp_server.py, install aiohttp (pip install aiohttp), and run it:

python aiohttp_server.py

Then send it a request from another terminal:

curl -s -H 'Content-Type: application/json' -d '{"jsonrpc": "2.0", "method": "ping", "id": 1}' http://localhost:8000/
Output
{"jsonrpc": "2.0", "result": "pong", "id": 1}

The jsonrpcclient quickstart sends the same request from Python.