Overview

This section provides the general overview of the library.

Installation

$ pip install bthlabs_jsonrpc_core

Usage

While this package is built to mostly support other integrations, it’s possible to use it directly to add a JSONRPC endpoint to an existing Web app.

Consider the following Flask app:

from bthlabs_jsonrpc_core import Executor, register_method
from flask import Flask, jsonify, request

app = Flask(__name__)


@register_method('hello')
def hello(who='World'):
    return f'Hello, {who}!'


@app.route('/rpc', methods=['POST'])
def post_rpc():
    executor = Executor()
    serializer = executor.execute(request.get_data())

    return jsonify(serializer.data)

This application will allow calling the hello JSONPRC method via the POST /rpc endpoint. This approach is limited, as it doesn’t provide the means of performing any access control and other checks, leaving the app to do this. In practice, it’s best to rely on framework integrations.

Calling Conventions

The JSONRPC 2.0 spec calls for two conventions for passing method parameters - by-position (using an array) or by-name (using a JSON object). BTHLabs JSONRPC implements both.

The hello method from the Flask app example could be called using the following payloads.

{
    "jsonrpc": "2.0",
    "id": "hello"
}

This payload would call the method without arguments. In this case, it would return Hello, World!.

{
    "jsonrpc": "2.0",
    "id": "hello",
    "params": ["JSONRPC"]
}

This payload would call the method with one positional argument. In this case, it would return Hello, JSONRPC!.

{
    "jsonrpc": "2.0",
    "id": "hello",
    "params": {"who": "JSONRPC"}
}

This payload would call the method with one keyword argument. In this case, it would return Hello, JSONRPC!.

While writing your methods, you should consider these conventions and specify your method signatures accordingly.