How to use JSON-RPC with Werkzeug?

werkzeug json

We’ll use Werkzeug to take JSON-RPC requests. It should respond to ‘ping’ with ‘pong’.

Install Werkzeug to take requests and jsonrpcserver to process them:

pip install werkzeug jsonrpcserver

Create a

from jsonrpcserver import method, Result, Success, dispatch
from werkzeug.serving import run_simple
from werkzeug.wrappers import Request, Response

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

def application(request):
    return Response(dispatch(, 200, mimetype="application/json")

if __name__ == "__main__":
    run_simple("localhost", 5000, application)

Start the server:

$ python
 * Running on http://localhost:5000/ (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}