Skip to content

Flask

from flask import Flask, Response, request

from jsonrpcserver import Result, Success, dispatch, method

app = Flask(__name__)
# Bigger requests get 413 Request Entity Too Large.
app.config["MAX_CONTENT_LENGTH"] = 1_000_000


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


@app.post("/")
def index() -> Response:
    # max_batch_size: see the Security page.
    if response := dispatch(request.get_data(as_text=True), max_batch_size=100):
        return Response(response, content_type="application/json")
    return Response(status=204)


if __name__ == "__main__":
    app.run(host="localhost", port=8000)

MAX_CONTENT_LENGTH makes Flask answer a bigger body with 413 before it's read. Flask has no limit by default. max_batch_size limits how many requests one batch can hold. See Security.

To give methods the request or the logged-in user, pass context. Context has a Flask example.

app.run starts Flask's development server. For production, run the app with a WSGI server such as Gunicorn, as the Flask docs describe.

Try it

Save the example as flask_server.py, install Flask (pip install flask), and run it:

python flask_server.py

Then send it a request from another terminal:

curl -s -H 'Content-Type: application/json' -d '{"jsonrpc": "2.0", "method": "ping", "id": 1}' http://localhost:8000/
Output
{"jsonrpc": "2.0", "result": "pong", "id": 1}

The jsonrpcclient quickstart sends the same request from Python.