API Reference#

Important

This part of the documentation covers only public classes, their methods and attributes. Private objects are only needed for internal use and accessing of them by hand is discouraged.

Routing user-defined functions#

class jsonrpc.Dispatcher(dict=None, /, **kwargs)#

The collections.UserDict subclass representing the storage of user-defined functions.

For example:

>>> dispatcher = Dispatcher()
>>> dispatcher["func"] = lambda: True
>>> dispatcher["func"]
<function <lambda> at 0x…>
register(user_function=None, *, function_name=None)#

Adds a user-defined function to the dispatcher.

Example usage:

>>> @dispatcher.register
... def truediv(a: float, b: float) -> float:
...     return a / b

Also you can pass the different function’s name:

>>> @dispatcher.register(function_name="sum")
... def _(a: float, b: float) -> float:
...     return a + b
Parameters:
  • user_function – The types.FunctionType object representing the user-defined function.

  • function_name – An optional function’s name. If it is omitted, attribute __name__ will be used instead.

Raises:

RuntimeError – If the user_function isn’t passed by the inspect.isfunction() method, or function with the provided name is already defined in the jsonrpc.Dispatcher class.

Returns:

The unmodified user_function object, passed in the parameters.

dispatch(function_name, /, *args, **kwargs)#

Invoke the user-defined function by passed in parameters function’s name.

Example usage:

>>> dispatcher = Dispatcher()
>>> dispatcher.dispatch("sum", a=12, b=34)
46
Parameters:
  • function_name – The user-defined function’s name.

  • args – Positional arguments for the provided function.

  • kwargs – Keyword arguments for the provided function.

Raises:

jsonrpc.Error – If the function doesn’t exists in the jsonrpc.Dispatcher class, passed invalid parameters or unexpected internal error has raised. See also jsonrpc.ErrorEnum.

Returns:

Result of execution the user-defined function.

Error handling#

class jsonrpc.ErrorEnum(value)#

An enumeration of error codes that indicates the error type that occurred.

PARSE_ERROR = -32700#

Error occurred due the serialization or deserialization.

INVALID_REQUEST = -32600#

Error occurred due the receiving an invalid jsonrpc.Request object.

METHOD_NOT_FOUND = -32601#

Error occurred due the invoking a missing user-function.

INVALID_PARAMETERS = -32602#

Error occurred due the receiving an invalid user-function’s arguments.

INTERNAL_ERROR = -32603#

Error occurred due the unexpected internal errors.

exception jsonrpc.Error(*, code, message, data=Undefined)#

Base class for all encountered errors in the JSON-RPC protocol.

code#

The int object that indicates the error type that occurred.

message#

The str object that contains a short description of the error.

data#

An any type of object that contains additional information about the error.

property json#

Returns the dict object needed for the serialization.

Example output:

>>> error: Error = Error(
...     code=ErrorEnum.INTERNAL_ERROR,
...     message="Unexpected error",
...     data={"additional": "information"}
... )
>>> error.json
{"code": -32603, "message": "Unexpected error", "data": {"additional": "information"}}

Requests & Responses#

class jsonrpc.Request(*, method, params=Undefined, request_id=Undefined)#

Base JSON-RPC request object.

method#

The str object containing the name of the method.

params#

The object of type list or dict that holds the parameter values to be used during the invocation of the method. May be omitted if provided method has no parameters for example.

request_id#

The str object or any type of numbers.Number object which represents an identifier of the request instance. May be omitted. If its value omitted, the request assumed to be a notification.

property args#

Returns the tuple object containing positional arguments of the method.

property kwargs#

Returns the dict object containing keyword arguments of the method.

property is_notification#

Returns True if the identifier of the request is omitted, False elsewise.

static from_json(obj, /)#

The static method for creating the jsonrpc.Request object from dict object. Unlike the jsonrpc.Request constructor, doesn’t raises any exceptions by validations, it returns the jsonrpc.Error as is.

Example usage:

>>> Request.from_json({"jsonrpc": "2.0", "method": "foobar", "id": 1})
Request(method="foobar", params=Undefined, request_id=1)
>>> Request.from_json({"not_jsonrpc": True})
Error(code=-32600, message="Invalid request object", data={"not_jsonrpc": True})
class jsonrpc.BatchRequest(initlist=None)#

The collections.UserList subclass representing the collection of jsonrpc.Request and jsonrpc.Error objects.

static from_json(iterable, /)#

The static method for creating the jsonrpc.BatchRequest object from collections.abc.Iterable of dict objects. Similar to jsonrpc.Request.from_json() function it doesn’t raises any exceptions.

Example usage:

>>> BatchRequest.from_json([
...     {"jsonrpc": "2.0", "method": "foobar", "id": 1},
...     {"not_jsonrpc": True}
... ])
BatchRequest([Request(…), Error(…)])
class jsonrpc.Response(*, body=Undefined, error=Undefined, response_id=Undefined)#

Base JSON-RPC response object.

body#

An any type of object that contains a result of successful processing the jsonrpc.Request object. This attribute must not be set if there an error has occurred.

error#

The jsonrpc.Error object representing an erroneous processing the jsonrpc.Request object. This attribute must not be set if no one error has occurred.

response_id#

The same attribute as jsonrpc.Request.request_id except that its value might be equal to None in erroneous responses.

property json#

Returns the dict object needed for the serialization.

Example successful response:

>>> response: Response = Response(body="foobar", response_id=65535)
>>> response.json
{"jsonrpc": "2.0", "result": "foobar", "id": 65535}

Example erroneous response:

>>> error: Error = Error(code=ErrorEnum.INTERNAL_ERROR, message="Unexpected error")
>>> response: Response = Response(error=error, response_id="6ba7b810")
>>> response.json
{"jsonrpc": "2.0", "error": {"code": -32603, "message": "Unexpected error"}, "id": "6ba7b810"}
class jsonrpc.BatchResponse(initlist=None)#

The collections.UserList subclass representing the collection of jsonrpc.Response objects.

property json#

Returns the list of dict objects needed for the serialization.

Example output:

>>> response: BatchResponse = BatchResponse([
...     Response(body="foobar", response_id=1024),
...     Response(
...         error=Error(code=ErrorEnum.INTERNAL_ERROR, message="Unexpected error"),
...         response_id="6ba7b810"
...     )
... ])
>>> response.json
[
    {"jsonrpc": "2.0", "result": "foobar", "id": 1024},
    {"jsonrpc": "2.0", "error": {"code": -32603, "message": "Unexpected error"}, "id": "6ba7b810"}
]

Data Serialization#

class jsonrpc.JSONSerializer#

Simple class for JSON serialization and deserialization.

DEFAULT_ENCODING = 'utf-8'#

Returns the name of the current default string encoding. Default value retrieves from the sys.getdefaultencoding().

serialize(obj, /)#

Returns the JSON representation of a value.

Parameters:

obj – An any type of object that must be JSON serializable.

Raises:

jsonrpc.Error – If any exception has occurred due the serialization or/and encoding to bytes.

Returns:

The bytes object containing the serialized Python data structure.

deserialize(obj, /)#

Returns the value encoded in JSON in appropriate Python type.

Parameters:

obj – The bytes object containing the serialized JSON document.

Raises:

jsonrpc.Error – If any exception has occurred due the deserialization or/and decoding from bytes.

Returns:

An any type of object containing the deserialized Python data structure.

class jsonrpc.PickleSerializer#

Simple class for the “Pickling” and “Unpickling” Python objects.

PROTOCOL_VERSION = 5#

Pickle protocol version used for the serialization. Defaults to pickle.HIGHEST_PROTOCOL.

serialize(obj, /)#

Returns the pickled representation of a value.

Parameters:

obj – An any type of object that must be serializable.

Raises:

jsonrpc.Error – If exception has occurred due the pickling.

Returns:

The bytes object containing the pickled object.

deserialize(obj, /)#

Returns the unpickled representation of a value.

Parameters:

obj – The bytes object containing the pickled object.

Raises:

jsonrpc.Error – If exception has occurred due the unpickling.

Returns:

An any type of object containing the deserialized Python data structure.

WSGI Entry Point#

class jsonrpc.WSGIHandler(dict=None, /, **kwargs)#

Base class representing the WSGI entry point. Its subclassing the collections.UserDict object for providing the user-defined data storage.

For example:

>>> app = WSGIHandler()
>>> app["my_private_key"] = "foobar"
>>> app["my_private_key"]
"foobar"
default_content_type = 'application/json'#

The default content type of the responses.

allowed_http_methods = ('POST', 'PUT')#

The list of HTTP request methods which are allowed to use.

dispatcher = Dispatcher({})#

Class variable representing the jsonrpc.Dispatcher object used by this class for routing user-defined functions by default.

serializer = JSONSerializer()#

Class variable representing the jsonrpc.JSONSerializer object used by this class for data serialization by default.