API Reference

ASGI Entry Point

class jsonrpc.ASGIHandler(*, title='jsonrpc-py', version='0.1.0', description=None, terms_of_service=None, contact=None, license=None, servers=None, components=None, external_docs=None, openrpc_url='/openrpc.json')

Base class representing the ASGI entry point.

title

The title of the API.

version

The version of the API.

description

A description of the API.

terms_of_service

A URL to the Terms of Service for the API.

contact

The contact information for the API.

license

The license information for the API.

servers

An array of servers, which provide connectivity information to a target server.

components

An element to hold various schemas for the specification.

external_docs

Additional external documentation.

openrpc_url

The URL where the OpenRPC schema will be served from.

dispatcher

The AsyncDispatcher object for this instance.

serializer

The JSONSerializer object for this instance.

events

The LifespanEvents object for this instance.

property openrpc

Returns the OpenRPC schema object.

exception jsonrpc.HTTPException(*, status)

Describes an exception that occurred during the processing of HTTP requests.

status

HTTP response status code.

Routing user-defined functions

class jsonrpc.AsyncDispatcher

A simple class for storing user-defined functions.

registry

The dict object storage of user-defined functions.

register(user_function=None, /, **kwargs)

Adds a user-defined function to the registry.

Parameters:
  • user_function – A user-defined function.

  • kwargs – Schema parameters of a function, also see Method parameters.

Returns:

The Function object that has the same signature as user_function object.

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

Invokes a user-defined function by the function name.

Parameters:
  • function_name – The name of function.

  • args – Positional arguments for the provided function.

  • kwargs – Keyword arguments for the provided function.

Raises:

jsonrpc.Error – If the function doesn’t exists, got invalid parameters or an unexpected internal error has occurred.

Returns:

Result of execution the user-defined function.

class jsonrpc.Function(*, callback, signature, schema)

Almost the same as a partial() function.

callback

The original Callable object.

signature

A Signature object of a function.

schema

A Method schema object of a function.

classmethod from_callable(user_function, /, **kwargs)

Constructs Function object for the given callable object.

Parameters:
  • user_function – A user-defined function.

  • kwargs – Schema parameters of a function, also see Method parameters.

Raises:

TypeError – If a user_function object is not a user-defined function.

Error handling

class jsonrpc.ErrorEnum(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)

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 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 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.

classmethod from_json(obj, /)

The class method for creating the Request object from dict object. Unlike the Request constructor, doesn’t raises any exceptions by validations, it returns the 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(iterable=())

A Collection of the Request and Error objects.

classmethod from_json(iterable, /)

The class method for creating the BatchRequest object from Iterable of dict objects. Similar to 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 Request object. This attribute must not be set if there an error has occurred.

error

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

response_id

The same attribute as 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(iterable=())

A Collection of the 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

A simple class for serializing and deserializing JSON.

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.

Lifespan

class jsonrpc.LifespanEvents

Simple class for storing the user-defined functions that running when application is initiated and shutting down.

startup_events

The WeakSet collection of startup functions.

shutdown_events

The WeakSet collection of shutdown functions.

on_startup(user_function, /)

Decorator for the adding a function which will be executed when application is initiated.

Example usage:

>>> @app.events.on_startup
... def startup_callback() -> None:
...     print("Some important message")
Parameters:

user_function – The Callable object representing the user-defined function.

Returns:

The unmodified user_function object, passed in the parameters.

on_shutdown(user_function, /)

Decorator for the adding a function which will be executed when application is shutting down.

Example usage:

>>> @app.events.on_shutdown
... async def shutdown_callback() -> None:
...     await important_function()
Parameters:

user_function – The Callable object representing the user-defined function.

Returns:

The unmodified user_function object, passed in the parameters.