How to use JSON-RPC with Tornado?

tornado json

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

Install Tornado to take requests and jsonrpcserver to process them:

pip install tornado jsonrpcserver

Create a

from jsonrpcserver import method, Result, Success, async_dispatch
from tornado import ioloop, web

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

class MainHandler(web.RequestHandler):
    async def post(self) -> None:
        request = self.request.body.decode()
        if response := await async_dispatch(request):

app = web.Application([(r"/", MainHandler)])

if __name__ == "__main__":

Start the server:

$ python

Test it

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