How to use JSON-RPC with Sanic?

sanic json

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

Install Sanic to take requests and Jsonrpcserver to process them:

pip install sanic jsonrpcserver

Create a

from sanic import Sanic
from sanic.request import Request
from sanic.response import json
from jsonrpcserver import Result, Success, dispatch_to_serializable, method

app = Sanic("JSON-RPC app")

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

@app.route("/", methods=["POST"])
async def test(request: Request):
    return json(dispatch_to_serializable(request.body))

if __name__ == "__main__":

Start the server:

$ python
[2021-08-19 20:54:48 +1000] [6671] [INFO] Goin' Fast @
[2021-08-19 20:54:48 +1000] [6671] [INFO] Starting worker [6671]

Test it

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