How to use JSON-RPC with Aiohttp?

flask json

We’ll use AioHTTP to take JSON-RPC requests. It should respond to “ping” with “pong”.

Install AioHTTP to take requests and jsonrpcserver to process them:

pip install aiohttp jsonrpcserver

Create a server.py:

from aiohttp import web
from jsonrpcserver import method, Result, Success, async_dispatch


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


async def handle(request):
    return web.Response(
        text=await async_dispatch(await request.text()), content_type="application/json"
    )


app = web.Application()
app.router.add_post("/", handle)

if __name__ == "__main__":
    web.run_app(app, port=5000)

Start the server:

$ python server.py
======== Running on http://0.0.0.0:5000/ ========
(Press CTRL+C to quit)

Test it

$ curl -X POST http://localhost:5000 -d '{"jsonrpc": "2.0", "method": "ping", "id": 1}'
{"jsonrpc": "2.0", "result": "pong", "id": 1}

Send JSON-RPC request with aiohttp

pip install aiohttp jsonrpcclient

Create a client.py:

import asyncio
import logging

from aiohttp import ClientSession
from jsonrpcclient import Ok, request, parse

async def main():
    async with ClientSession() as session:
        async with session.post(
            "http://localhost:5000", json=request("ping")
        ) as response:
            parsed = parse(await response.json())
            if isinstance(parsed, Ok):
                print(parsed.result)
            else:
                logging.error(parsed.message)

asyncio.get_event_loop().run_until_complete(main())
$ python client.py
pong