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

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

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
======== Running on ========
(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

import asyncio
import logging

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

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

$ python