API Reference¶
ASGI Entry Point¶
- class jsonrpc.ASGIHandler(*, title='jsonrpc-py', version='0.1.0', description=Undefined, terms_of_service=Undefined, contact=Undefined, license=Undefined, servers=<factory>, 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.
- openrpc_url¶
The URL where the OpenRPC schema will be served from.
- dispatcher¶
The
jsonrpc.AsyncDispatcher
object for this instance.
- serializer¶
The
jsonrpc.JSONSerializer
object for this instance.
- events¶
The
jsonrpc.LifespanEvents
object for this instance.
- property openrpc¶
Returns the
jsonrpc.openrpc.OpenRPC
schema object.
Routing user-defined functions¶
- class jsonrpc.AsyncDispatcher¶
A simple class for storing user-defined functions.
- registry¶
The
collections.OrderedDict
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
jsonrpc.openrpc.Method
parameters.
- Returns:
The
jsonrpc.Function
object that has the same signature asuser_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
functools.partial()
function.- callback¶
The original
collections.abc.Callable
object.
- signature¶
A
inspect.Signature
object of a function.
- schema¶
A
jsonrpc.openrpc.Method
schema object of a function.
- classmethod from_callable(user_function, /, **kwargs)¶
Constructs
jsonrpc.Function
object for the given callable object.- Parameters:
user_function – A user-defined function.
kwargs – Schema parameters of a function, also see
jsonrpc.openrpc.Method
parameters.
- Raises:
TypeError – If a
user_function
object is not a user-defined function.
Error handling¶
- class jsonrpc.ErrorEnum(value, names=None, *, 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
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.
- 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.
- params¶
The object of type
list
ordict
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 ofnumbers.Number
object which represents an identifier of the request instance. May be omitted. If its value omitted, the request assumed to be a notification.
- classmethod from_json(obj, /)¶
The class method for creating the
jsonrpc.Request
object fromdict
object. Unlike thejsonrpc.Request
constructor, doesn’t raises any exceptions by validations, it returns thejsonrpc.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 ofjsonrpc.Request
andjsonrpc.Error
objects.- classmethod from_json(iterable, /)¶
The class method for creating the
jsonrpc.BatchRequest
object fromcollections.abc.Iterable
ofdict
objects. Similar tojsonrpc.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 thejsonrpc.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 toNone
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 ofjsonrpc.Response
objects.- property json¶
Returns the
list
ofdict
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
weakref.WeakSet
collection of startup functions.
- shutdown_events¶
The
weakref.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
collections.abc.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
collections.abc.Callable
object representing the user-defined function.- Returns:
The unmodified
user_function
object, passed in the parameters.