API Documentation

This section provides the API documentation for BTHLabs JSONRPC - Core.

Decorators

bthlabs_jsonrpc_core.register_method(method: str, namespace: Optional[str] = None) Callable

Registers the decorated function as JSONRPC method in namespace. If namespace is omitted, the function will be registered in the default namespace.

Example:

@register_method('example')
def example(a, b):
    return a + b

Exceptions

exception bthlabs_jsonrpc_core.BaseJSONRPCError(data=None)

Base class for JSONRPC exceptions.

If data is provided, it’ll be added to the exception’s response payload.

ERROR_CODE: int = -32001

Error code

ERROR_MESSAGE: str = 'JSONRPC Error'

Error message

to_rpc() dict

Returns payload for JSONRPCSerializer.

exception bthlabs_jsonrpc_core.JSONRPCAccessDeniedError(data=None)

Access denied error

ERROR_CODE: int = -32003

Error code

ERROR_MESSAGE: str = 'Access denied'

Error message

exception bthlabs_jsonrpc_core.JSONRPCInternalError(data=None)

Internal error

ERROR_CODE: int = -32603

Error code

ERROR_MESSAGE: str = 'Internal error'

Error message

exception bthlabs_jsonrpc_core.JSONRPCParseError(data=None)

Parse error

ERROR_CODE: int = -32700

Error code

ERROR_MESSAGE: str = 'Parse error'

Error message

exception bthlabs_jsonrpc_core.JSONRPCSerializerError(data=None)

Serializer error

ERROR_CODE: int = -32002

Error code

ERROR_MESSAGE: str = 'JSONRPCSerializer error'

Error message

Executor

class bthlabs_jsonrpc_core.Executor(namespace=None)

Executor is the main interface for the integrations. It processes the JSONRPC request, executes the calls and returns the responses.

namespace will be used to look up called methods in the registry. If omitted, it’ll fall back to the default namespace.

Example:

def rpc_handler(request):
    executor = Executor()
    serializer = executor.execute(request.body)

    return JSONResponse(serializer.data)
before_call(method: str, args: list, kwargs: dict)

Hook for subclasses to perform additional operations before executing the call.

If this method raises a subclass of BaseJSONRPCError, it’ll be used to construct the response object directly. Any other exception will be wrapped in JSONRPCInternalError.

The default implementation does nothing.

deserialize_data(data: bytes) Any

Deserializes data and returns the result.

Raises JSONRPCParseError if there was an error in the process. Subclasses should also raise this exception, so it can be resulting response object conforms to the spec.

enrich_args(args: list) list

Hook for subclasses to pass additional args to the handler. The default implementation returns the args verbatim.

Example:

class ExampleExecutor(Executor):
    def enrich_args(self, args):
        return ['spam', *args]
enrich_kwargs(kwargs: dict) dict

Hook for subclasses to pass additional kwaargs to the handler. The default implementation returns the kwargs verbatim.

Example:

class ExampleExecutor(Executor):
    def enrich_kwargs(self, kwargs):
        return {'spam': True, **kwargs}
execute(payload: Any) Optional[bthlabs_jsonrpc_core.serializer.JSONRPCSerializer]

Executes the JSONRPC request in payload.

Returns an instance of JSONRPCSerializer or None if the list of responses is empty.

list_methods(*args, **kwargs) list[str]

The handler for system.list_methods internal method.

Returns list of methods this Executor can handle.

serializer

alias of bthlabs_jsonrpc_core.serializer.JSONRPCSerializer

Serializer

class bthlabs_jsonrpc_core.JSONRPCSerializer(data)

Serializer for JSONRPC responses.

This class is responsible for making the respones JSON-serializable. Sequence types are all converted to lists. Dict-like types are all converted to plain dicts. Simple types (bool, float, int and str) and None are returned as they are.

Datetime values are converted to strings using the ISO format. UUID and Decimal values are explicitly coerced to strings.

For values of other types, the serializer will try to invoke their to_rpc() method. If that fails, the serializer will raise JSONRPCSerializerError.

Example:

spam = ['eggs', {'spam': False}, Decimal('42.0')]
serializer = JSONRPCSerializer(spam)
print(serializer.data)

Example with to_rpc():

class Spam:
    def to_rpc(self):
        return {
            'spam': True
        }

spam = ['eggs', Spam(), Decimal('42.0')]
serializer = JSONRPCSerializer(spam)
print(serializer.data)
property data: Any

The serialized data.