Developer Interface¶
Extensible JSON-RPC client/server library.
Common¶
Client and server common functions, types and classes that implements JSON-RPC protocol itself and agnostic to any transport protocol layer (http, socket, amqp) and server-side implementation.
-
class
pjrpc.common.
Request
(method, params=None, id=None)¶ JSON-RPC version 2.0 request.
- Parameters
method – method name
params – method parameters
id – request identifier
-
classmethod
from_json
(json_data)¶ Deserializes a request from json data.
-
property
id
¶ Request identifier.
-
property
method
¶ Request method name.
-
property
params
¶ Request method parameters.
-
to_json
()¶ Serializes the request to json data.
-
property
is_notification
¶ Returns
True
if the request is a notification e.g. id isNone
.
-
class
pjrpc.common.
Response
(id, result=UNSET, error=UNSET)¶ JSON-RPC version 2.0 response.
- Parameters
id – response identifier
result – response result
error – response error
-
classmethod
from_json
(json_data, error_cls=<class 'pjrpc.common.exceptions.JsonRpcError'>)¶ Deserializes a response from json data.
- Parameters
- Returns
response object
- Raises
pjrpc.common.exceptions.DeserializationError
if format is incorrect- Return type
pjrpc.common.v20.Response
-
property
id
¶ Response identifier.
-
property
result
¶ Response result. If the response has not succeeded raises an exception deserialized from the error field.
-
property
error
¶ Response error. If the response has succeeded returns
pjrpc.common.common.UNSET
.
-
property
is_success
¶ Returns
True
if the response has succeeded.
-
property
is_error
¶ Returns
True
if the response has not succeeded.
Returns the request related response object if the response has been received from the server otherwise returns
None
.
-
class
pjrpc.common.
BatchRequest
(*requests, strict=True)¶ JSON-RPC 2.0 batch request.
- Parameters
requests – requests to be added to the batch
strict – if
True
checks response identifier uniqueness
-
classmethod
from_json
(data)¶ Deserializes a batch request from json data.
-
append
(request)¶ Appends a request to the batch.
- Parameters
request (pjrpc.common.v20.Request) –
- Return type
-
extend
(requests)¶ Extends a batch with requests.
- Parameters
requests (Iterable[pjrpc.common.v20.Request]) –
- Return type
-
to_json
()¶ Serializes the request to json data.
-
property
is_notification
¶ Returns
True
if all the request in the batch are notifications.
-
class
pjrpc.common.
BatchResponse
(*responses, error=UNSET, strict=True)¶ JSON-RPC 2.0 batch response.
- Parameters
responses – responses to be added to the batch
strict – if
True
checks response identifier uniqueness
-
classmethod
from_json
(json_data, error_cls=<class 'pjrpc.common.exceptions.JsonRpcError'>)¶ Deserializes a batch response from json data.
-
property
error
¶ Response error. If the response has succeeded returns
pjrpc.common.common.UNSET
.
-
property
is_success
¶ Returns
True
if the response has succeeded.
-
property
is_error
¶ Returns
True
if the request has not succeeded. Note that it is not the same aspjrpc.common.BatchResponse.has_error
. is_error indicates that the batch request failed at all, while has_error indicates that one of the requests in the batch failed.
-
property
has_error
¶ Returns
True
if any response has an error.
-
property
result
¶ Returns the batch result as a tuple. If any response of the batch has an error raises an exception of the first errored response.
Returns the request related response object if the response has been received from the server otherwise returns
None
.
-
append
(response)¶ Appends a response to the batch.
- Parameters
response (pjrpc.common.v20.Response) –
- Return type
-
extend
(responses)¶ Extends the batch with the responses.
- Parameters
responses (Iterable[pjrpc.common.v20.Response]) –
- Return type
-
class
pjrpc.common.
UnsetType
¶ Sentinel object. Used to distinct unset (missing) values from
None
ones.
-
class
pjrpc.common.
JSONEncoder
(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)¶ Library default JSON encoder. Encodes request, response and error objects to be json serializable. All custom encoders should be inherited from it.
-
default
(o)¶ Implement this method in a subclass such that it returns a serializable object for
o
, or calls the base implementation (to raise aTypeError
).For example, to support arbitrary iterators, you could implement default like this:
def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return JSONEncoder.default(self, o)
- Parameters
o (Any) –
- Return type
Any
-
Exceptions¶
Definition of package exceptions and JSON-RPC protocol errors.
-
exception
pjrpc.common.exceptions.
BaseError
¶ Base package error. All package errors are inherited from it.
-
exception
pjrpc.common.exceptions.
IdentityError
¶ Raised when a batch requests/responses identifiers are not unique or missing.
-
exception
pjrpc.common.exceptions.
DeserializationError
¶ Request/response deserializatoin error. Raised when request/response json has incorrect format.
-
class
pjrpc.common.exceptions.
JsonRpcErrorMeta
(name, bases, dct)¶ pjrpc.common.exceptions.JsonRpcError
metaclass. Builds a mapping from an error code number to an error class inherited from apjrpc.common.exceptions.JsonRpcError
.
-
exception
pjrpc.common.exceptions.
JsonRpcError
(code=None, message=None, data=UNSET)¶ JSON-RPC protocol error. For more information see Error object. All JSON-RPC protocol errors are inherited from it.
- Parameters
-
classmethod
from_json
(json_data)¶ Deserializes an error from json data. If data format is not correct
ValueError
is raised.
-
exception
pjrpc.common.exceptions.
ClientError
(code=None, message=None, data=UNSET)¶ Raised when a client sent an incorrect request.
-
exception
pjrpc.common.exceptions.
ParseError
(code=None, message=None, data=UNSET)¶ Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.
-
exception
pjrpc.common.exceptions.
InvalidRequestError
(code=None, message=None, data=UNSET)¶ The JSON sent is not a valid request object.
-
exception
pjrpc.common.exceptions.
MethodNotFoundError
(code=None, message=None, data=UNSET)¶ The method does not exist / is not available.
-
exception
pjrpc.common.exceptions.
InvalidParamsError
(code=None, message=None, data=UNSET)¶ Invalid method parameter(s).
-
exception
pjrpc.common.exceptions.
InternalError
(code=None, message=None, data=UNSET)¶ Internal JSON-RPC error.
Identifier generators¶
Builtin request id generators. Implements several identifier types and generation strategies.
-
pjrpc.common.generators.
sequential
(start=1, step=1)¶ Sequential id generator. Returns consecutive values starting from start with step step.
-
pjrpc.common.generators.
randint
(a, b)¶ Random integer id generator. Returns random integers between a and b.
-
pjrpc.common.generators.
random
(length=8, chars='0123456789abcdefghijklmnopqrstuvwxyz')¶ Random string id generator. Returns random strings of length length using alphabet chars.
Client¶
JSON-RPC client.
-
class
pjrpc.client.
AbstractClient
(request_class=<class 'pjrpc.common.v20.Request'>, response_class=<class 'pjrpc.common.v20.Response'>, batch_request_class=<class 'pjrpc.common.v20.BatchRequest'>, batch_response_class=<class 'pjrpc.common.v20.BatchResponse'>, error_cls=<class 'pjrpc.common.exceptions.JsonRpcError'>, id_gen_impl=<function sequential>, json_loader=<function loads>, json_dumper=<function dumps>, json_encoder=<class 'pjrpc.common.common.JSONEncoder'>, json_decoder=None, strict=True, request_args=None, tracers=())¶ Abstract JSON-RPC client.
- Parameters
request_class – request class
response_class – response class
batch_request_class – batch request class
batch_response_class – batch response class
id_gen_impl – identifier generator
json_loader – json loader
json_dumper – json dumper
json_encoder – json encoder
json_decoder – json decoder
error_cls – JSON-RPC error base class
strict – if
True
checks that a request and a response identifiers match
-
class
Proxy
(client)¶ Proxy object. Provides syntactic sugar to make method call using dot notation.
- Parameters
client – JSON-RPC client instance
-
property
proxy
¶ Clint proxy object.
-
property
batch
¶ Client batch wrapper.
-
notify
(method, *args, _trace_ctx=namespace(), **kwargs)¶ Makes a notification request
- Parameters
method (str) – method name
args (Any) – method positional arguments
kwargs (Any) – method named arguments
_trace_ctx – tracers request context
-
call
(method, *args, _trace_ctx=namespace(), **kwargs)¶ Makes JSON-RPC call.
- Parameters
method (str) – method name
args (Any) – method positional arguments
kwargs (Any) – method named arguments
_trace_ctx (types.SimpleNamespace) – tracers request context
- Returns
response result
- Return type
Optional[pjrpc.common.v20.Response]
-
send
(request, _trace_ctx=namespace(), **kwargs)¶ Sends a JSON-RPC request.
- Parameters
request (pjrpc.common.v20.Request) – request instance
kwargs (Any) – additional client request argument
_trace_ctx (types.SimpleNamespace) – tracers request context
- Returns
response instance
- Return type
Optional[pjrpc.common.v20.Response]
-
class
pjrpc.client.
AbstractAsyncClient
(request_class=<class 'pjrpc.common.v20.Request'>, response_class=<class 'pjrpc.common.v20.Response'>, batch_request_class=<class 'pjrpc.common.v20.BatchRequest'>, batch_response_class=<class 'pjrpc.common.v20.BatchResponse'>, error_cls=<class 'pjrpc.common.exceptions.JsonRpcError'>, id_gen_impl=<function sequential>, json_loader=<function loads>, json_dumper=<function dumps>, json_encoder=<class 'pjrpc.common.common.JSONEncoder'>, json_decoder=None, strict=True, request_args=None, tracers=())¶ Abstract asynchronous JSON-RPC client.
-
property
batch
¶ Client batch wrapper.
-
async
send
(request, _trace_ctx=namespace(), **kwargs)¶ Sends a JSON-RPC request.
- Parameters
request (pjrpc.common.v20.Request) – request instance
kwargs (Any) – additional client request argument
_trace_ctx (types.SimpleNamespace) – tracers request context
- Returns
response instance
- Return type
Optional[pjrpc.common.v20.Response]
-
async
call
(method, *args, _trace_ctx=namespace(), **kwargs)¶ Makes JSON-RPC call.
- Parameters
method (str) – method name
args (Any) – method positional arguments
kwargs (Any) – method named arguments
_trace_ctx (types.SimpleNamespace) – tracers request context
- Returns
response result
- Return type
Any
-
property
-
class
pjrpc.client.
LoggingTracer
(logger=<RootLogger root (WARNING)>, level=10)¶ JSON-RPC client logging tracer.
-
on_request_begin
(trace_context, request)¶ Handler called before JSON-RPC request begins.
- Parameters
trace_context (types.SimpleNamespace) – request trace context
request (pjrpc.common.v20.Request) – JSON-RPC request
- Return type
-
on_request_end
(trace_context, request, response)¶ Handler called after JSON-RPC request ends.
- Parameters
trace_context (types.SimpleNamespace) – request trace context
request (pjrpc.common.v20.Request) – JSON-RPC request
response (pjrpc.common.v20.Response) – JSON-RPC response
- Return type
-
on_error
(trace_context, request, error)¶ Handler called when JSON-RPC request failed.
- Parameters
trace_context (types.SimpleNamespace) – request trace context
request (Union[pjrpc.common.v20.Request, pjrpc.common.v20.BatchRequest]) – JSON-RPC request
error (BaseException) – raised exception
- Return type
-
-
class
pjrpc.client.
Tracer
¶ JSON-RPC client tracer.
-
on_request_begin
(trace_context, request)¶ Handler called before JSON-RPC request begins.
- Parameters
trace_context (types.SimpleNamespace) – request trace context
request (pjrpc.common.v20.Request) – JSON-RPC request
- Return type
-
on_request_end
(trace_context, request, response)¶ Handler called after JSON-RPC request ends.
- Parameters
trace_context (types.SimpleNamespace) – request trace context
request (pjrpc.common.v20.Request) – JSON-RPC request
response (pjrpc.common.v20.Response) – JSON-RPC response
- Return type
-
on_error
(trace_context, request, error)¶ Handler called when JSON-RPC request failed.
- Parameters
trace_context (types.SimpleNamespace) – request trace context
request (Union[pjrpc.common.v20.Request, pjrpc.common.v20.BatchRequest]) – JSON-RPC request
error (BaseException) – raised exception
- Return type
-
Backends¶
-
class
pjrpc.client.backend.requests.
Client
(url, session=None, **kwargs)¶ Requests library client backend.
- Parameters
url – url to be used as JSON-RPC endpoint.
session – custom session to be used instead of
requests.Session
kwargs – parameters to be passed to
pjrpc.client.AbstractClient
-
class
pjrpc.client.backend.aiohttp.
Client
(url, session_args=None, session=None, **kwargs)¶ Aiohttp library client backend.
- Parameters
url – url to be used as JSON-RPC endpoint
session_args – additional
aiohttp.ClientSession
argumentssession – custom session to be used instead of
aiohttp.ClientSession
-
class
pjrpc.client.backend.kombu.
Client
(broker_url, queue_name=None, conn_args=None, exchange_name=None, exchange_args=None, routing_key=None, result_queue_name=None, result_queue_args=None, **kwargs)¶ kombu based JSON-RPC client. Note: the client is not thread-safe.
- Parameters
broker_url – broker connection url
conn_args – broker connection arguments.
queue_name – queue name to publish requests to
exchange_name – exchange to publish requests to. If
None
default exchange is usedexchange_args – exchange arguments
routing_key – reply message routing key. If
None
queue name is usedresult_queue_name – result queue name. If
None
random exclusive queue is declared for each requestconn_args – additional connection arguments
kwargs – parameters to be passed to
pjrpc.client.AbstractClient
-
class
pjrpc.client.backend.aio_pika.
Client
(broker_url, queue_name=None, conn_args=None, exchange_name=None, exchange_args=None, routing_key=None, result_queue_name=None, result_queue_args=None, **kwargs)¶ aio_pika based JSON-RPC client.
- Parameters
broker_url – broker connection url
conn_args – broker connection arguments.
queue_name – queue name to publish requests to
exchange_name – exchange to publish requests to. If
None
default exchange is usedexchange_args – exchange arguments
routing_key – reply message routing key. If
None
queue name is usedresult_queue_name – result queue name. If
None
random exclusive queue is declared for each requestconn_args – additional connection arguments
kwargs – parameters to be passed to
pjrpc.client.AbstractClient
Tracer¶
-
class
pjrpc.client.tracer.
Tracer
¶ JSON-RPC client tracer.
-
on_request_begin
(trace_context, request)¶ Handler called before JSON-RPC request begins.
- Parameters
trace_context (types.SimpleNamespace) – request trace context
request (pjrpc.common.v20.Request) – JSON-RPC request
- Return type
-
on_request_end
(trace_context, request, response)¶ Handler called after JSON-RPC request ends.
- Parameters
trace_context (types.SimpleNamespace) – request trace context
request (pjrpc.common.v20.Request) – JSON-RPC request
response (pjrpc.common.v20.Response) – JSON-RPC response
- Return type
-
on_error
(trace_context, request, error)¶ Handler called when JSON-RPC request failed.
- Parameters
trace_context (types.SimpleNamespace) – request trace context
request (Union[pjrpc.common.v20.Request, pjrpc.common.v20.BatchRequest]) – JSON-RPC request
error (BaseException) – raised exception
- Return type
-
-
class
pjrpc.client.tracer.
LoggingTracer
(logger=<RootLogger root (WARNING)>, level=10)¶ JSON-RPC client logging tracer.
-
on_request_begin
(trace_context, request)¶ Handler called before JSON-RPC request begins.
- Parameters
trace_context (types.SimpleNamespace) – request trace context
request (pjrpc.common.v20.Request) – JSON-RPC request
- Return type
-
on_request_end
(trace_context, request, response)¶ Handler called after JSON-RPC request ends.
- Parameters
trace_context (types.SimpleNamespace) – request trace context
request (pjrpc.common.v20.Request) – JSON-RPC request
response (pjrpc.common.v20.Response) – JSON-RPC response
- Return type
-
on_error
(trace_context, request, error)¶ Handler called when JSON-RPC request failed.
- Parameters
trace_context (types.SimpleNamespace) – request trace context
request (Union[pjrpc.common.v20.Request, pjrpc.common.v20.BatchRequest]) – JSON-RPC request
error (BaseException) – raised exception
- Return type
-
Integrations¶
Server¶
JSON-RPC server package.
-
class
pjrpc.server.
AsyncDispatcher
(*, request_class=<class 'pjrpc.common.v20.Request'>, response_class=<class 'pjrpc.common.v20.Response'>, batch_request=<class 'pjrpc.common.v20.BatchRequest'>, batch_response=<class 'pjrpc.common.v20.BatchResponse'>, json_loader=<function loads>, json_dumper=<function dumps>, json_encoder=<class 'pjrpc.server.dispatcher.JSONEncoder'>, json_decoder=None, middlewares=(), error_handlers={})¶ Asynchronous method dispatcher.
-
async
dispatch
(request_text, context=None)¶ Deserializes request, dispatches it to the required method and serializes the result.
-
async
-
class
pjrpc.server.
Dispatcher
(*, request_class=<class 'pjrpc.common.v20.Request'>, response_class=<class 'pjrpc.common.v20.Response'>, batch_request=<class 'pjrpc.common.v20.BatchRequest'>, batch_response=<class 'pjrpc.common.v20.BatchResponse'>, json_loader=<function loads>, json_dumper=<function dumps>, json_encoder=<class 'pjrpc.server.dispatcher.JSONEncoder'>, json_decoder=None, middlewares=(), error_handlers={})¶ Method dispatcher.
- Parameters
request_class – JSON-RPC request class
response_class – JSON-RPC response class
batch_request – JSON-RPC batch request class
batch_response – JSON-RPC batch response class
json_loader – request json loader
json_dumper – response json dumper
json_encoder – response json encoder
json_decoder – request json decoder
middlewares – request middlewares
error_handlers – request error handlers
-
add
(method, name=None, context=None)¶ Adds method to the registry.
-
add_methods
(*methods)¶ Adds methods to the registry.
- Parameters
methods (Union[pjrpc.server.dispatcher.MethodRegistry, pjrpc.server.dispatcher.Method, Callable]) – method list. Each method may be an instance of
pjrpc.server.MethodRegistry
,pjrpc.server.Method
or plain function- Return type
-
view
(view)¶ Adds class based view to the registry.
- Parameters
view (Type[pjrpc.server.dispatcher.ViewMixin]) – view to be added
- Return type
-
dispatch
(request_text, context=None)¶ Deserializes request, dispatches it to the required method and serializes the result.
-
class
pjrpc.server.
JSONEncoder
(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)¶ Server JSON encoder. All custom server encoders should be inherited from it.
-
default
(o)¶ Implement this method in a subclass such that it returns a serializable object for
o
, or calls the base implementation (to raise aTypeError
).For example, to support arbitrary iterators, you could implement default like this:
def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return JSONEncoder.default(self, o)
- Parameters
o (Any) –
- Return type
Any
-
-
class
pjrpc.server.
Method
(method, name=None, context=None)¶ JSON-RPC method wrapper. Stores method itself and some metainformation.
- Parameters
method – method
name – method name
context – context name
-
class
pjrpc.server.
MethodRegistry
(prefix=None)¶ Method registry.
- Parameters
prefix – method name prefix to be used for naming containing methods
-
get
(item)¶ Returns a method from the registry by name.
- Parameters
item (str) – method name
- Returns
found method or None
- Return type
Optional[pjrpc.server.dispatcher.Method]
-
add
(maybe_method=None, name=None, context=None)¶ Decorator adding decorated method to the registry.
- Parameters
maybe_method (Optional[Callable]) – method or None
name (Optional[str]) – method name to be used instead of __name__ attribute
context (Optional[Any]) – parameter name to be used as an application context
- Returns
decorated method or decorator
- Return type
Callable
-
add_methods
(*methods)¶ Adds methods to the registry.
- Parameters
methods (Union[Callable, pjrpc.server.dispatcher.Method]) – methods to be added. Each one can be an instance of
pjrpc.server.Method
or plain method- Return type
-
view
(maybe_view=None, context=None, prefix=None)¶ Methods view decorator.
- Parameters
maybe_view (Optional[Type[pjrpc.server.dispatcher.ViewMixin]]) – view class instance or None
context (Optional[Any]) – application context name
prefix (Optional[str]) – view methods prefix
- Returns
decorator or decorated view
- Return type
Union[pjrpc.server.dispatcher.ViewMixin, Callable]
-
class
pjrpc.server.
ViewMixin
¶ Simple class based method handler mixin. Exposes all public methods.
Integrations¶
aiohttp¶
aiohttp JSON-RPC server integration.
-
class
pjrpc.server.integration.aiohttp.
Application
(path='', spec=None, app=None, **kwargs)¶ aiohttp based JSON-RPC server.
- Parameters
path – JSON-RPC handler base path
app_args – arguments to be passed to
aiohttp.web.Application
kwargs – arguments to be passed to the dispatcher
pjrpc.server.AsyncDispatcher
-
property
app
¶ aiohttp application.
-
property
dispatcher
¶ JSON-RPC method dispatcher.
-
property
endpoints
¶ JSON-RPC application registered endpoints.
-
add_endpoint
(prefix, subapp=None, **kwargs)¶ Adds additional endpoint.
- Parameters
prefix (str) – endpoint prefix
subapp (Optional[aiohttp.web_app.Application]) – aiohttp subapp the endpoint will be served on
kwargs (Any) – arguments to be passed to the dispatcher
pjrpc.server.Dispatcher
- Returns
dispatcher
- Return type
pjrpc.server.dispatcher.Dispatcher
flask¶
Flask JSON-RPC extension.
-
class
pjrpc.server.integration.flask.
JsonRPC
(path, spec=None, **kwargs)¶ Flask framework JSON-RPC extension class.
- Parameters
path – JSON-RPC handler base path
spec – JSON-RPC specification
kwargs – arguments to be passed to the dispatcher
pjrpc.server.Dispatcher
-
property
dispatcher
¶ JSON-RPC method dispatcher.
-
property
endpoints
¶ JSON-RPC application registered endpoints.
-
add_endpoint
(prefix, blueprint=None, **kwargs)¶ Adds additional endpoint.
- Parameters
prefix (str) – endpoint prefix
blueprint (Optional[flask.blueprints.Blueprint]) – flask blueprint the endpoint will be served on
kwargs (Any) – arguments to be passed to the dispatcher
pjrpc.server.Dispatcher
- Returns
dispatcher
- Return type
pjrpc.server.dispatcher.Dispatcher
kombu¶
kombu JSON-RPC server integration.
-
class
pjrpc.server.integration.kombu.
Executor
(broker_url, queue_name, conn_args=None, queue_args=None, publish_args=None, prefetch_count=0, **kwargs)¶ kombu based JSON-RPC server.
- Parameters
broker_url – broker connection url
queue_name – requests queue name
conn_args – additional connection arguments
queue_args – queue arguments
publish_args – message publish additional arguments
prefetch_count – worker prefetch count
kwargs – dispatcher additional arguments
-
property
dispatcher
¶ JSON-RPC method dispatcher.
aio_pika¶
-
class
pjrpc.server.integration.aio_pika.
Executor
(broker_url, queue_name, prefetch_count=0, **kwargs)¶ aio_pika based JSON-RPC server.
- Parameters
broker_url – broker connection url
queue_name – requests queue name
prefetch_count – worker prefetch count
kwargs – dispatcher additional arguments
-
property
dispatcher
¶ JSON-RPC method dispatcher.
-
async
start
(queue_args=None)¶ Starts executor.
werkzeug¶
-
class
pjrpc.server.integration.werkzeug.
JsonRPC
(path='', **kwargs)¶ werkzeug server JSON-RPC integration.
- Parameters
path – JSON-RPC handler base path
kwargs – arguments to be passed to the dispatcher
pjrpc.server.Dispatcher
-
property
dispatcher
¶ JSON-RPC method dispatcher.
Validators¶
JSON-RPC method parameters validators.
-
class
pjrpc.server.validators.
BaseValidator
¶ Base method parameters validator. Uses
inspect.signature()
for validation.-
validate
(maybe_method=None, **kwargs)¶ Decorator marks a method the parameters of which to be validated when calling it using JSON-RPC protocol.
- Parameters
maybe_method (Optional[Callable]) – method the parameters of which to be validated or
None
if called as @validate(…)kwargs (Any) – validator arguments
- Return type
Callable
-
validate_method
(method, params, exclude=(), **kwargs)¶ Validates params against method signature.
- Parameters
- Raises
- Returns
bound method parameters
- Return type
Dict[str, Any]
-
bind
(signature, params)¶ Binds parameters to method. :param signature: method to bind parameters to :param params: parameters to be bound
- Raises
ValidationError is parameters binding failed
- Returns
bound parameters
- Parameters
signature (inspect.Signature) –
- Return type
-
-
exception
pjrpc.server.validators.
ValidationError
¶ Method parameters validation error. Raised when parameters validation failed.
jsonschema¶
-
class
pjrpc.server.validators.jsonschema.
JsonSchemaValidator
(**kwargs)¶ Parameters validator based on jsonschema library.
- Parameters
kwargs – default jsonschema validator arguments
pydantic¶
-
class
pjrpc.server.validators.pydantic.
PydanticValidator
(coerce=True, **config_args)¶ Parameters validator based on pydantic library. Uses python type annotations for parameters validation.
- Parameters
coerce – if
True
returns converted (coerced) parameters according to parameter type annotation otherwise returns parameters as is
-
validate_method
(method, params, exclude=(), **kwargs)¶ Validates params against method using
pydantic
validator.- Parameters
- Returns
coerced parameters if coerce flag is
True
otherwise parameters as is- Raises
ValidationError
- Return type
Dict[str, Any]
-
build_validation_schema
(signature)¶ Builds pydantic model based validation schema from method signature.
- Parameters
signature (inspect.Signature) – method signature to build schema for
- Returns
validation schema
- Return type
Dict[str, Any]
Specification¶
-
class
pjrpc.server.specs.
JSONEncoder
(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)¶ Schema JSON encoder.
-
default
(o)¶ Implement this method in a subclass such that it returns a serializable object for
o
, or calls the base implementation (to raise aTypeError
).For example, to support arbitrary iterators, you could implement default like this:
def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return JSONEncoder.default(self, o)
- Parameters
o (Any) –
- Return type
Any
-
-
class
pjrpc.server.specs.
BaseUI
¶ Base UI.
-
class
pjrpc.server.specs.
Specification
(path='/spec.json', ui=None, ui_path=None)¶ JSON-RPC specification.
- Parameters
path – specification url path suffix
ui – specification ui instance
ui_path – specification ui url path suffix
-
property
path
¶ Returns specification url path.
-
property
ui
¶ Returns ui instance.
-
property
ui_path
¶ Returns specification ui url path.
-
abstract
schema
(path, methods=(), methods_map={})¶ Returns specification schema.
- Parameters
path (str) – methods endpoint path
methods (Iterable[pjrpc.server.dispatcher.Method]) – methods list the specification is generated for
methods_map (Dict[str, Iterable[pjrpc.server.dispatcher.Method]]) – methods map the specification is generated for. Each item is a mapping from a prefix to methods on which the methods will be served
- Return type
extractors¶
-
class
pjrpc.server.specs.extractors.
Schema
(schema, required=True, summary=UNSET, description=UNSET, deprecated=UNSET, definitions=UNSET)¶ Method parameter/result schema.
-
class
pjrpc.server.specs.extractors.
Example
(params, result, version='2.0', summary=UNSET, description=UNSET)¶ Method usage example.
-
class
pjrpc.server.specs.extractors.
Tag
(name, description=UNSET, externalDocs=UNSET)¶ A list of method tags.
-
class
pjrpc.server.specs.extractors.
Error
(code, message, data=UNSET)¶ Defines an application level error.
-
class
pjrpc.server.specs.extractors.
BaseSchemaExtractor
¶ Base method schema extractor.
-
extract_params_schema
(method, exclude=())¶ Extracts method parameters schema.
- Parameters
method (Callable) –
exclude (Iterable[str]) –
- Return type
-
extract_result_schema
(method)¶ Extracts method result schema.
- Parameters
method (Callable) –
- Return type
-
extract_description
(method)¶ Extracts method description.
- Parameters
method (Callable) –
- Return type
Union[pjrpc.common.common.UnsetType, str]
-
extract_summary
(method)¶ Extracts method summary.
- Parameters
method (Callable) –
- Return type
Union[pjrpc.common.common.UnsetType, str]
-
extract_errors_schema
(method)¶ Extracts method errors schema.
- Parameters
method (Callable) –
- Return type
Union[pjrpc.common.common.UnsetType, List[pjrpc.server.specs.extractors.Error]]
Extracts method tags.
- Parameters
method (Callable) –
- Return type
Union[pjrpc.common.common.UnsetType, List[pjrpc.server.specs.extractors.Tag]]
-
extract_examples
(method)¶ Extracts method usage examples.
- Parameters
method (Callable) –
- Return type
Union[pjrpc.common.common.UnsetType, List[pjrpc.server.specs.extractors.Example]]
-
-
class
pjrpc.server.specs.extractors.pydantic.
PydanticSchemaExtractor
(ref_template='#/components/schemas/{model}')¶ Pydantic method specification extractor.
-
extract_params_schema
(method, exclude=())¶ Extracts method parameters schema.
- Parameters
method (Callable) –
exclude (Iterable[str]) –
- Return type
-
extract_result_schema
(method)¶ Extracts method result schema.
- Parameters
method (Callable) –
- Return type
-
schemas¶
OpenAPI Specification generator. See https://swagger.io/specification/.
-
class
pjrpc.server.specs.openapi.
Contact
(name=UNSET, url=UNSET, email=UNSET)¶ Contact information for the exposed API.
- Parameters
name – the identifying name of the contact person/organization
url – the URL pointing to the contact information
email – the email address of the contact person/organization
-
class
pjrpc.server.specs.openapi.
License
(name, url=UNSET)¶ License information for the exposed API.
- Parameters
name – the license name used for the API
url – a URL to the license used for the API
-
class
pjrpc.server.specs.openapi.
Info
(title, version, description=UNSET, contact=UNSET, license=UNSET, termsOfService=UNSET)¶ Metadata about the API.
- Parameters
title – the title of the application
version – the version of the OpenAPI document
description – a short description of the application
contact – the contact information for the exposed API
license – the license information for the exposed API
termsOfService – a URL to the Terms of Service for the API
-
class
pjrpc.server.specs.openapi.
ServerVariable
(default, enum=UNSET, description=UNSET)¶ An object representing a Server Variable for server URL template substitution.
- Parameters
default – the default value to use for substitution, which SHALL be sent if an alternate value is not supplied
enum – an enumeration of string values to be used if the substitution options are from a limited set
description – an optional description for the server variable
-
class
pjrpc.server.specs.openapi.
Server
(url, description=UNSET, variables=UNSET)¶ Connectivity information of a target server.
- Parameters
url – a URL to the target host
description – an optional string describing the host designated by the URL
-
class
pjrpc.server.specs.openapi.
ExternalDocumentation
(url, description=UNSET)¶ Allows referencing an external resource for extended documentation.
- Parameters
url – a short description of the target documentation.
description – the URL for the target documentation
-
class
pjrpc.server.specs.openapi.
Tag
(name, description=UNSET, externalDocs=UNSET)¶ A list of tags for API documentation control. Tags can be used for logical grouping of methods by resources or any other qualifier.
- Parameters
name – the name of the tag
externalDocs – additional external documentation for this tag
description – a short description for the tag
-
class
pjrpc.server.specs.openapi.
SecuritySchemeType
(value)¶ The type of the security scheme.
-
APIKEY
= 'apiKey'¶
-
HTTP
= 'http'¶
-
OAUTH2
= 'oauth2'¶
-
OPENID_CONNECT
= 'openIdConnect'¶
-
-
class
pjrpc.server.specs.openapi.
ApiKeyLocation
(value)¶ The location of the API key.
-
QUERY
= 'query'¶
-
HEADER
= 'header'¶
-
COOKIE
= 'cookie'¶
-
-
class
pjrpc.server.specs.openapi.
OAuthFlow
(authorizationUrl, tokenUrl, scopes, refreshUrl=UNSET)¶ Configuration details for a supported OAuth Flow.
- Parameters
authorizationUrl – the authorization URL to be used for this flow
tokenUrl – the token URL to be used for this flow
refreshUrl – the URL to be used for obtaining refresh tokens
scopes – the available scopes for the OAuth2 security scheme
-
class
pjrpc.server.specs.openapi.
OAuthFlows
(implicit=UNSET, password=UNSET, clientCredentials=UNSET, authorizationCode=UNSET)¶ Configuration of the supported OAuth Flows.
- Parameters
implicit – configuration for the OAuth Implicit flow
password – configuration for the OAuth Resource Owner Password flow
clientCredentials – configuration for the OAuth Client Credentials flow
authorizationCode – configuration for the OAuth Authorization Code flow
-
class
pjrpc.server.specs.openapi.
SecurityScheme
(type, scheme, name=UNSET, location=UNSET, bearerFormat=UNSET, flows=UNSET, openIdConnectUrl=UNSET, description=UNSET)¶ Defines a security scheme that can be used by the operations.
- Parameters
type – the type of the security scheme
name – the name of the header, query or cookie parameter to be used
location – the location of the API key
scheme – the name of the HTTP Authorization scheme to be used in the Authorization header
bearerFormat – a hint to the client to identify how the bearer token is formatted
flows – an object containing configuration information for the flow types supported
openIdConnectUrl –
description – a short description for security scheme
-
class
pjrpc.server.specs.openapi.
Components
(securitySchemes=UNSET, schemas=<factory>)¶ Holds a set of reusable objects for different aspects of the OAS.
- Parameters
securitySchemes – an object to hold reusable Security Scheme Objects
schemas – the definition of input and output data types
-
class
pjrpc.server.specs.openapi.
Error
(code, message, data=UNSET)¶ Defines an application level error.
- Parameters
code – a Number that indicates the error type that occurred
message – a String providing a short description of the error
data – a Primitive or Structured value that contains additional information about the error
-
class
pjrpc.server.specs.openapi.
MethodExample
(params, result, version='2.0', summary=UNSET, description=UNSET)¶ Method usage example.
- Parameters
params – example parameters
result – example result
name – name for the example pairing
summary – short description for the example pairing
description – a verbose explanation of the example pairing
-
class
pjrpc.server.specs.openapi.
ExampleObject
(value, summary=UNSET, description=UNSET, externalValue=UNSET)¶ Method usage example.
- Parameters
value – embedded literal example
summary – short description for the example.
description – long description for the example
externalValue – a URL that points to the literal example
-
class
pjrpc.server.specs.openapi.
MediaType
(schema, examples=UNSET)¶ Each Media Type Object provides schema and examples for the media type identified by its key.
- Parameters
schema – the schema defining the content.
example – example of the media type
-
class
pjrpc.server.specs.openapi.
Response
(description, content=UNSET)¶ A container for the expected responses of an operation.
- Parameters
description – a short description of the response
content – a map containing descriptions of potential response payloads
-
class
pjrpc.server.specs.openapi.
RequestBody
(content, required=UNSET, description=UNSET)¶ Describes a single request body.
- Parameters
content – the content of the request body
required – determines if the request body is required in the request
description – a brief description of the request body
-
class
pjrpc.server.specs.openapi.
ParameterLocation
(value)¶ The location of the parameter.
-
QUERY
= 'query'¶
-
HEADER
= 'header'¶
-
PATH
= 'path'¶
-
COOKIE
= 'cookie'¶
-
-
class
pjrpc.server.specs.openapi.
StyleType
(value)¶ Describes how the parameter value will be serialized depending on the type of the parameter value.
-
MATRIX
= 'matrix'¶
-
LABEL
= 'label'¶
-
FORM
= 'form'¶
-
SIMPLE
= 'simple'¶
-
SPACE_DELIMITED
= 'spaceDelimited'¶
-
PIPE_DELIMITED
= 'pipeDelimited'¶
-
DEEP_OBJECT
= 'deepObject'¶
-
-
class
pjrpc.server.specs.openapi.
Parameter
(name, location, description=UNSET, required=UNSET, deprecated=UNSET, allowEmptyValue=UNSET, style=UNSET, explode=UNSET, allowReserved=UNSET, schema=UNSET, examples=UNSET, content=UNSET)¶ Describes a single operation parameter.
- Parameters
name – the name of the parameter
location – the location of the parameter
description – a brief description of the parameter
required – determines whether this parameter is mandatory
deprecated – a parameter is deprecated and SHOULD be transitioned out of usage
allowEmptyValue – the ability to pass empty-valued parameters
style – describes how the parameter value will be serialized depending on the type of the parameter value
explode – when this is true, parameter values of type array or object generate separate parameters for each value of the array or key-value pair of the map
allowReserved – determines whether the parameter value SHOULD allow reserved characters, as defined by RFC3986 :/?#[]@!$&’()*+,;= to be included without percent-encoding
schema – the schema defining the type used for the parameter.
examples – examples of the parameter’s potential value
content – a map containing the representations for the parameter
-
class
pjrpc.server.specs.openapi.
Operation
(responses, requestBody=UNSET, tags=UNSET, summary=UNSET, description=UNSET, externalDocs=UNSET, deprecated=UNSET, servers=UNSET, security=UNSET, parameters=UNSET)¶ Describes a single API operation on a path.
- Parameters
tags – a list of tags for API documentation control
summary – a short summary of what the operation does
description – a verbose explanation of the operation behavior
externalDocs – additional external documentation for this operation
requestBody – the request body applicable for this operation
responses – the list of possible responses as they are returned from executing this operation
deprecated – declares this operation to be deprecated
servers – an alternative server array to service this operation
security – a declaration of which security mechanisms can be used for this operation
-
class
pjrpc.server.specs.openapi.
Path
(get=UNSET, put=UNSET, post=UNSET, delete=UNSET, options=UNSET, head=UNSET, patch=UNSET, trace=UNSET, summary=UNSET, description=UNSET, servers=UNSET)¶ Describes the interface for the given method name.
- Parameters
summary – an optional, string summary, intended to apply to all operations in this path
description – an optional, string description, intended to apply to all operations in this path
servers – an alternative server array to service all operations in this path
-
pjrpc.server.specs.openapi.
annotate
(params_schema=UNSET, result_schema=UNSET, errors=UNSET, examples=UNSET, tags=UNSET, summary=UNSET, description=UNSET, external_docs=UNSET, deprecated=UNSET, security=UNSET, parameters=UNSET)¶ Adds Open Api specification annotation to the method.
- Parameters
params_schema (Dict[str, pjrpc.server.specs.extractors.Schema]) – method parameters JSON schema
result_schema (pjrpc.server.specs.extractors.Schema) – method result JSON schema
errors (List[Union[pjrpc.server.specs.openapi.Error, Type[pjrpc.common.exceptions.JsonRpcError]]]) – method errors
examples (List[pjrpc.server.specs.openapi.MethodExample]) – method usage examples
tags (List[str]) – a list of tags for method documentation control
summary (str) – a short summary of what the method does
description (str) – a verbose explanation of the method behavior
external_docs (pjrpc.server.specs.openapi.ExternalDocumentation) – an external resource for extended documentation
deprecated (bool) – declares this method to be deprecated
security (List[Dict[str, List[str]]]) – a declaration of which security mechanisms can be used for the method
parameters (List[pjrpc.server.specs.openapi.Parameter]) – a list of parameters that are applicable for the method
-
class
pjrpc.server.specs.openapi.
OpenAPI
(info, path='/openapi.json', servers=UNSET, external_docs=UNSET, tags=UNSET, security=UNSET, security_schemes=UNSET, openapi='3.0.0', schema_extractor=None, ui=None, ui_path='/ui/')¶ OpenAPI Specification.
- Parameters
info – provides metadata about the API
servers – an array of Server Objects, which provide connectivity information to a target server
external_docs – additional external documentation
openapi – the semantic version number of the OpenAPI Specification version that the OpenAPI document uses
tags – a list of tags used by the specification with additional metadata
security – a declaration of which security mechanisms can be used across the API
schema_extractor – method specification extractor
path – specification url path
security_schemes – an object to hold reusable Security Scheme Objects
ui – web ui instance
ui_path – wet ui path
-
schema
(path, methods=(), methods_map={})¶ Returns specification schema.
- Parameters
path (str) – methods endpoint path
methods (Iterable[pjrpc.server.dispatcher.Method]) – methods list the specification is generated for
methods_map (Dict[str, Iterable[pjrpc.server.dispatcher.Method]]) – methods map the specification is generated for. Each item is a mapping from a prefix to methods on which the methods will be served
- Return type
-
class
pjrpc.server.specs.openapi.
SwaggerUI
(**configs)¶ Swagger UI.
- Parameters
config – documentation configurations (see https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md).
-
class
pjrpc.server.specs.openapi.
RapiDoc
(**configs)¶ RapiDoc UI.
- Parameters
config – documentation configurations (see https://mrin9.github.io/RapiDoc/api.html). Be aware that configuration parameters should be in snake case, for example: parameter heading-text should be passed as heading_text)
-
class
pjrpc.server.specs.openapi.
ReDoc
(**configs)¶ ReDoc UI.
- Parameters
config – documentation configurations (see https://github.com/Redocly/redoc#configuration). Be aware that configuration parameters should be in snake case, for example: parameter heading-text should be passed as heading_text)
OpenRPC specification generator. See https://spec.open-rpc.org/.
-
class
pjrpc.server.specs.openrpc.
Contact
(name=UNSET, url=UNSET, email=UNSET)¶ Contact information for the exposed API.
- Parameters
name – the identifying name of the contact person/organization
url – the URL pointing to the contact information
email – the email address of the contact person/organization
-
class
pjrpc.server.specs.openrpc.
License
(name, url=UNSET)¶ License information for the exposed API.
- Parameters
name – the license name used for the API
url – a URL to the license used for the API
-
class
pjrpc.server.specs.openrpc.
Info
(title, version, description=UNSET, contact=UNSET, license=UNSET, termsOfService=UNSET)¶ Metadata about the API.
- Parameters
title – the title of the application
version – the version of the OpenRPC document
description – a verbose description of the application
contact – the contact information for the exposed API
license – the license information for the exposed API
termsOfService – a URL to the Terms of Service for the API
-
class
pjrpc.server.specs.openrpc.
Server
(name, url, summary=UNSET, description=UNSET)¶ Connectivity information of a target server.
- Parameters
name – a name to be used as the canonical name for the server.
url – a URL to the target host
summary – a short summary of what the server is
description – an optional string describing the host designated by the URL
-
class
pjrpc.server.specs.openrpc.
ExternalDocumentation
(url, description=UNSET)¶ Allows referencing an external resource for extended documentation.
- Parameters
url – A verbose explanation of the target documentation
description – The URL for the target documentation. Value MUST be in the format of a URL
-
class
pjrpc.server.specs.openrpc.
Tag
(name, summary=UNSET, description=UNSET, externalDocs=UNSET)¶ A list of tags for API documentation control. Tags can be used for logical grouping of methods by resources or any other qualifier.
- Parameters
name – the name of the tag
summary – a short summary of the tag
description – a verbose explanation for the tag
externalDocs – additional external documentation for this tag
-
class
pjrpc.server.specs.openrpc.
ExampleObject
(value, name, summary=UNSET, description=UNSET)¶ The ExampleObject object is an object the defines an example.
- Parameters
value – embedded literal example
name – canonical name of the example
summary – short description for the example
description – a verbose explanation of the example
-
class
pjrpc.server.specs.openrpc.
MethodExample
(name, params, result, summary=UNSET, description=UNSET)¶ The example Pairing object consists of a set of example params and result.
- Parameters
params – example parameters
result – example result
name – name for the example pairing
summary – short description for the example pairing
description – a verbose explanation of the example pairing
-
class
pjrpc.server.specs.openrpc.
ContentDescriptor
(name, schema, summary=UNSET, description=UNSET, required=UNSET, deprecated=UNSET)¶ Content Descriptors are objects that describe content. They are reusable ways of describing either parameters or result.
- Parameters
name – name of the content that is being described
schema – schema that describes the content. The Schema Objects MUST follow the specifications outline in the JSON Schema Specification 7 (https://json-schema.org/draft-07/json-schema-release-notes.html)
summary – a short summary of the content that is being described
description – a verbose explanation of the content descriptor behavior
required – determines if the content is a required field
deprecated – specifies that the content is deprecated and SHOULD be transitioned out of usage
-
class
pjrpc.server.specs.openrpc.
Error
(code, message, data=UNSET)¶ Defines an application level error.
- Parameters
code – a Number that indicates the error type that occurred
message – a String providing a short description of the error
data – a Primitive or Structured value that contains additional information about the error
-
class
pjrpc.server.specs.openrpc.
ParamStructure
(value)¶ The expected format of the parameters.
-
BY_NAME
= 'by-name'¶
-
BY_POSITION
= 'by-position'¶
-
EITHER
= 'either'¶
-
-
class
pjrpc.server.specs.openrpc.
MethodInfo
(name, params, result, errors=UNSET, paramStructure=UNSET, examples=UNSET, summary=UNSET, description=UNSET, tags=UNSET, deprecated=UNSET, externalDocs=UNSET, servers=UNSET)¶ Describes the interface for the given method name.
- Parameters
name – the canonical name for the method
params – a list of parameters that are applicable for this method
result – the description of the result returned by the method
errors – a list of custom application defined errors that MAY be returned
examples – method usage examples
summary – a short summary of what the method does
description – a verbose explanation of the method behavior
tags – a list of tags for API documentation control
deprecated – declares this method to be deprecated
paramStructure – the expected format of the parameters
externalDocs – additional external documentation for this method
servers – an alternative servers array to service this method
-
class
pjrpc.server.specs.openrpc.
Components
(schemas=<factory>)¶ Set of reusable objects for different aspects of the OpenRPC.
- Parameters
schemas – reusable Schema Objects
-
pjrpc.server.specs.openrpc.
annotate
(params_schema=UNSET, result_schema=UNSET, errors=UNSET, examples=UNSET, summary=UNSET, description=UNSET, tags=UNSET, deprecated=UNSET)¶ Adds JSON-RPC method to the API specification.
- Parameters
params_schema (List[pjrpc.server.specs.openrpc.ContentDescriptor]) – a list of parameters that are applicable for this method
result_schema (pjrpc.server.specs.openrpc.ContentDescriptor) – the description of the result returned by the method
errors (List[Union[pjrpc.server.specs.openrpc.Error, Type[pjrpc.common.exceptions.JsonRpcError]]]) – a list of custom application defined errors that MAY be returned
examples (List[pjrpc.server.specs.openrpc.MethodExample]) – method usage example
summary (str) – a short summary of what the method does
description (str) – a verbose explanation of the method behavior
tags (List[Union[pjrpc.server.specs.openrpc.Tag, str]]) – a list of tags for API documentation control
deprecated (bool) – declares this method to be deprecated
-
class
pjrpc.server.specs.openrpc.
OpenRPC
(info, path='/openrpc.json', servers=UNSET, external_docs=UNSET, openrpc='1.0.0', schema_extractor=None)¶ OpenRPC Specification.
- Parameters
info – specification information
path – specification url path
servers – connectivity information
external_docs – additional external documentation
openrpc – the semantic version number of the OpenRPC Specification version that the OpenRPC document uses
schema_extractor – method specification extractor
-
schema
(path, methods=(), methods_map={})¶ Returns specification schema.
- Parameters
path (str) – methods endpoint path
methods (Iterable[pjrpc.server.dispatcher.Method]) – methods list the specification is generated for
methods_map (Dict[str, Iterable[pjrpc.server.dispatcher.Method]]) – methods map the specification is generated for. Each item is a mapping from a prefix to methods on which the methods will be served
- Return type