How to use JSON-RPC with Flask?
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 server.py
:
from flask import Flask, Response, request
from jsonrpcserver import method, Result, Success, dispatch
app = Flask(__name__)
@method
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__":
app.run()
Start the server:
$ python server.py
* 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}