How to use JSON-RPC with Tornado?
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 server.py
:
from jsonrpcserver import method, Result, Success, async_dispatch
from tornado import ioloop, web
@method
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):
self.write(response)
app = web.Application([(r"/", MainHandler)])
if __name__ == "__main__":
app.listen(5000)
ioloop.IOLoop.current().start()
Start the server:
$ python server.py
Test it
$ curl -X POST http://localhost:5000 -d '{"jsonrpc": "2.0", "method": "ping", "id": 1}'
{"jsonrpc": "2.0", "result": "pong", "id": 1}