How to use JSON-RPC with Flask?

flask json

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

Install Flask to take requests and jsonrpcserver to process them:

pip install flask jsonrpcserver

Create a

from flask import Flask, Response, request
from jsonrpcserver import method, Result, Success, dispatch

app = Flask(__name__)

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

@app.route("/", methods=["POST"])
def index():
    return Response(
        dispatch(request.get_data().decode()), content_type="application/json"

if __name__ == "__main__":

Start the server:

$ python
 * Restarting with stat
 * Debugger is active!
 * Debugger pin code: 216-262-392

Test it

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