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: str, params: Union[list, dict, None] = None, id: Union[int, str, None] = None)¶ JSON-RPC version 2.0 request.
Parameters: - method – method name
- params – method parameters
- id – request identifier
-
classmethod
from_json
(json_data: Union[str, int, float, dict, bool, list, tuple, set, None]) → pjrpc.common.v20.Request¶ Deserializes a request from json data.
Parameters: json_data – data the request to be deserialized from Returns: request object Raises: pjrpc.common.exceptions.DeserializationError
if format is incorrect
-
id
¶ Request identifier.
-
method
¶ Request method name.
-
params
¶ Request method parameters.
-
to_json
() → Union[str, int, float, dict, bool, list, tuple, set, None]¶ Serializes the request to json data.
Returns: json data
-
is_notification
¶ Returns
True
if the request is a notification e.g. id isNone
.
-
class
pjrpc.common.
Response
(id: Union[int, str, None], result: Union[pjrpc.common.common.UnsetType, Any] = UNSET, error: Union[pjrpc.common.common.UnsetType, pjrpc.common.exceptions.JsonRpcError] = UNSET)¶ JSON-RPC version 2.0 response.
Parameters: - id – response identifier
- result – response result
- error – response error
-
classmethod
from_json
(json_data: Union[str, int, float, dict, bool, list, tuple, set, None], error_cls: Type[pjrpc.common.exceptions.JsonRpcError] = <class 'pjrpc.common.exceptions.JsonRpcError'>) → pjrpc.common.v20.Response¶ Deserializes a response from json data.
Parameters: - json_data – data the response to be deserialized from
- error_cls – error class
Returns: response object
Raises: pjrpc.common.exceptions.DeserializationError
if format is incorrect
-
id
¶ Response identifier.
-
result
¶ Response result. If the response has not succeeded raises an exception deserialized from the error field.
-
error
¶ Response error. If the response has succeeded returns
pjrpc.common.common.UNSET
.
-
is_success
¶ Returns
True
if the response has succeeded.
-
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
.
-
to_json
() → Union[str, int, float, dict, bool, list, tuple, set, None]¶ Serializes the response to json data.
Returns: json data
-
class
pjrpc.common.
BatchRequest
(*requests, strict: bool = 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: Union[str, int, float, dict, bool, list, tuple, set, None]) → pjrpc.common.v20.BatchRequest¶ Deserializes a batch request from json data.
Parameters: data – data the request to be deserialized from Returns: batch request object
-
append
(request: pjrpc.common.v20.Request) → None¶ Appends a request to the batch.
-
extend
(requests: Iterable[pjrpc.common.v20.Request]) → None¶ Extends a batch with requests.
-
to_json
() → Union[str, int, float, dict, bool, list, tuple, set, None]¶ Serializes the request to json data.
Returns: json data
-
is_notification
¶ Returns
True
if all the request in the batch are notifications.
-
class
pjrpc.common.
BatchResponse
(*responses, error: Union[pjrpc.common.common.UnsetType, pjrpc.common.exceptions.JsonRpcError] = UNSET, strict: bool = 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: Union[str, int, float, dict, bool, list, tuple, set, None], error_cls: Type[pjrpc.common.exceptions.JsonRpcError] = <class 'pjrpc.common.exceptions.JsonRpcError'>) → pjrpc.common.v20.BatchResponse¶ Deserializes a batch response from json data.
Parameters: - json_data – data the response to be deserialized from
- error_cls – error class
Returns: batch response object
-
error
¶ Response error. If the response has succeeded returns
pjrpc.common.common.UNSET
.
-
is_success
¶ Returns
True
if the response has succeeded.
-
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.
-
has_error
¶ Returns
True
if any response has an error.
-
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: pjrpc.common.v20.Response) → None¶ Appends a response to the batch.
-
extend
(responses: Iterable[pjrpc.common.v20.Response]) → None¶ Extends the batch with the responses.
-
to_json
() → Union[str, int, float, dict, bool, list, tuple, set, None]¶ Serializes the batch response to json data.
Returns: json data
-
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: Any) → Any¶ 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)
-
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
¶ 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: Optional[int] = None, message: Optional[str] = None, data: Union[pjrpc.common.common.UnsetType, Any] = UNSET)¶ JSON-RPC protocol error. For more information see Error object. All JSON-RPC protocol errors are inherited from it.
Parameters: - code – number that indicates the error type
- message – short description of the error
- data – value that contains additional information about the error. May be omitted.
-
classmethod
from_json
(json_data: Union[str, int, float, dict, bool, list, tuple, set, None]) → pjrpc.common.exceptions.JsonRpcError¶ Deserializes an error from json data. If data format is not correct
ValueError
is raised.Parameters: json_data – json data the error to be deserialized from Returns: deserialized error Raises: pjrpc.common.exceptions.DeserializationError
if format is incorrect
-
to_json
() → Union[str, int, float, dict, bool, list, tuple, set, None]¶ Serializes the error to a dict.
Returns: serialized error
-
exception
pjrpc.common.exceptions.
ClientError
(code: Optional[int] = None, message: Optional[str] = None, data: Union[pjrpc.common.common.UnsetType, Any] = UNSET)¶ Raised when a client sent an incorrect request.
-
exception
pjrpc.common.exceptions.
ParseError
(code: Optional[int] = None, message: Optional[str] = None, data: Union[pjrpc.common.common.UnsetType, Any] = 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: Optional[int] = None, message: Optional[str] = None, data: Union[pjrpc.common.common.UnsetType, Any] = UNSET)¶ The JSON sent is not a valid request object.
-
exception
pjrpc.common.exceptions.
MethodNotFoundError
(code: Optional[int] = None, message: Optional[str] = None, data: Union[pjrpc.common.common.UnsetType, Any] = UNSET)¶ The method does not exist / is not available.
-
exception
pjrpc.common.exceptions.
InvalidParamsError
(code: Optional[int] = None, message: Optional[str] = None, data: Union[pjrpc.common.common.UnsetType, Any] = UNSET)¶ Invalid method parameter(s).
-
exception
pjrpc.common.exceptions.
InternalError
(code: Optional[int] = None, message: Optional[str] = None, data: Union[pjrpc.common.common.UnsetType, Any] = UNSET)¶ Internal JSON-RPC error.
-
exception
pjrpc.common.exceptions.
ServerError
(code: Optional[int] = None, message: Optional[str] = None, data: Union[pjrpc.common.common.UnsetType, Any] = UNSET)¶ Reserved for implementation-defined server-errors. Codes from -32000 to -32099.
Identifier generators¶
Builtin request id generators. Implements several identifier types and generation strategies.
-
pjrpc.common.generators.
sequential
(start: int = 1, step: int = 1) → Generator[int, None, None]¶ Sequential id generator. Returns consecutive values starting from start with step step.
-
pjrpc.common.generators.
randint
(a: int, b: int) → Generator[int, None, None]¶ Random integer id generator. Returns random integers between a and b.
-
pjrpc.common.generators.
random
(length: int = 8, chars: str = '0123456789abcdefghijklmnopqrstuvwxyz') → Generator[str, None, None]¶ Random string id generator. Returns random strings of length length using alphabet chars.
-
pjrpc.common.generators.
uuid
() → Generator[uuid.UUID, None, None]¶ UUID id generator. Returns random UUIDs.
Client¶
JSON-RPC client.
-
class
pjrpc.client.
AbstractClient
(request_class: Type[pjrpc.common.v20.Request] = <class 'pjrpc.common.v20.Request'>, response_class: Type[pjrpc.common.v20.Response] = <class 'pjrpc.common.v20.Response'>, batch_request_class: Type[pjrpc.common.v20.BatchRequest] = <class 'pjrpc.common.v20.BatchRequest'>, batch_response_class: Type[pjrpc.common.v20.BatchResponse] = <class 'pjrpc.common.v20.BatchResponse'>, error_cls: Type[pjrpc.common.exceptions.JsonRpcError] = <class 'pjrpc.common.exceptions.JsonRpcError'>, id_gen_impl: Callable[[...], Generator[Union[int, str], None, None]] = <function sequential>, json_loader: Callable = <function loads>, json_dumper: Callable = <function dumps>, json_encoder: Type[pjrpc.common.common.JSONEncoder] = <class 'pjrpc.common.common.JSONEncoder'>, json_decoder: Optional[json.decoder.JSONDecoder] = None, strict: bool = True, request_args: Optional[Dict[str, Any]] = None, tracers: Iterable[pjrpc.client.tracer.Tracer] = ())¶ 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: pjrpc.client.client.AbstractClient)¶ Proxy object. Provides syntactic sugar to make method call using dot notation.
Parameters: client – JSON-RPC client instance
-
proxy
¶ Clint proxy object.
-
batch
¶ Client batch wrapper.
-
notify
(method: str, *args, _trace_ctx=namespace(), **kwargs)¶ Makes a notification request
Parameters: - method – method name
- args – method positional arguments
- kwargs – method named arguments
- _trace_ctx – tracers request context
-
call
(method: str, *args, _trace_ctx: types.SimpleNamespace = namespace(), **kwargs) → Optional[pjrpc.common.v20.Response]¶ Makes JSON-RPC call.
Parameters: - method – method name
- args – method positional arguments
- kwargs – method named arguments
- _trace_ctx – tracers request context
Returns: response result
-
send
(request: pjrpc.common.v20.Request, _trace_ctx: types.SimpleNamespace = namespace(), **kwargs) → Optional[pjrpc.common.v20.Response]¶ Sends a JSON-RPC request.
Parameters: - request – request instance
- kwargs – additional client request argument
- _trace_ctx – tracers request context
Returns: response instance
-
class
pjrpc.client.
AbstractAsyncClient
(request_class: Type[pjrpc.common.v20.Request] = <class 'pjrpc.common.v20.Request'>, response_class: Type[pjrpc.common.v20.Response] = <class 'pjrpc.common.v20.Response'>, batch_request_class: Type[pjrpc.common.v20.BatchRequest] = <class 'pjrpc.common.v20.BatchRequest'>, batch_response_class: Type[pjrpc.common.v20.BatchResponse] = <class 'pjrpc.common.v20.BatchResponse'>, error_cls: Type[pjrpc.common.exceptions.JsonRpcError] = <class 'pjrpc.common.exceptions.JsonRpcError'>, id_gen_impl: Callable[[...], Generator[Union[int, str], None, None]] = <function sequential>, json_loader: Callable = <function loads>, json_dumper: Callable = <function dumps>, json_encoder: Type[pjrpc.common.common.JSONEncoder] = <class 'pjrpc.common.common.JSONEncoder'>, json_decoder: Optional[json.decoder.JSONDecoder] = None, strict: bool = True, request_args: Optional[Dict[str, Any]] = None, tracers: Iterable[pjrpc.client.tracer.Tracer] = ())¶ Abstract asynchronous JSON-RPC client.
-
batch
¶ Client batch wrapper.
-
call
(method: str, *args, _trace_ctx: types.SimpleNamespace = namespace(), **kwargs) → Any¶ Makes JSON-RPC call.
Parameters: - method – method name
- args – method positional arguments
- kwargs – method named arguments
- _trace_ctx – tracers request context
Returns: response result
-
send
(request: pjrpc.common.v20.Request, _trace_ctx: types.SimpleNamespace = namespace(), **kwargs) → Optional[pjrpc.common.v20.Response]¶ Sends a JSON-RPC request.
Parameters: - request – request instance
- kwargs – additional client request argument
- _trace_ctx – tracers request context
Returns: response instance
-
-
class
pjrpc.client.
LoggingTracer
(logger: logging.Logger = <RootLogger root (WARNING)>, level: int = 10)¶ JSON-RPC client logging tracer.
-
on_request_begin
(trace_context: types.SimpleNamespace, request: pjrpc.common.v20.Request) → None¶ Handler called before JSON-RPC request begins.
Parameters: - trace_context – request trace context
- request – JSON-RPC request
-
on_request_end
(trace_context: types.SimpleNamespace, request: pjrpc.common.v20.Request, response: pjrpc.common.v20.Response) → None¶ Handler called after JSON-RPC request ends.
Parameters: - trace_context – request trace context
- request – JSON-RPC request
- response – JSON-RPC response
-
on_error
(trace_context: types.SimpleNamespace, request: Union[pjrpc.common.v20.Request, pjrpc.common.v20.BatchRequest], error: BaseException) → None¶ Handler called when JSON-RPC request failed.
Parameters: - trace_context – request trace context
- request – JSON-RPC request
- error – raised exception
-
-
class
pjrpc.client.
Tracer
¶ JSON-RPC client tracer.
-
on_request_begin
(trace_context: types.SimpleNamespace, request: pjrpc.common.v20.Request) → None¶ Handler called before JSON-RPC request begins.
Parameters: - trace_context – request trace context
- request – JSON-RPC request
-
on_request_end
(trace_context: types.SimpleNamespace, request: pjrpc.common.v20.Request, response: pjrpc.common.v20.Response) → None¶ Handler called after JSON-RPC request ends.
Parameters: - trace_context – request trace context
- request – JSON-RPC request
- response – JSON-RPC response
-
on_error
(trace_context: types.SimpleNamespace, request: Union[pjrpc.common.v20.Request, pjrpc.common.v20.BatchRequest], error: BaseException) → None¶ Handler called when JSON-RPC request failed.
Parameters: - trace_context – request trace context
- request – JSON-RPC request
- error – raised exception
-
Backends¶
-
class
pjrpc.client.backend.requests.
Client
(url: str, session: Optional[requests.sessions.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
-
close
() → None¶ Closes the current http session.
-
class
pjrpc.client.backend.aiohttp.
Client
(url: str, session_args: Optional[Dict[str, Any]] = None, session: Optional[aiohttp.client.ClientSession] = None, **kwargs)¶ Aiohttp library client backend.
Parameters: - url – url to be used as JSON-RPC endpoint
- session_args – additional
aiohttp.ClientSession
arguments - session – custom session to be used instead of
aiohttp.ClientSession
-
close
() → None¶ Closes current http session.
-
class
pjrpc.client.backend.kombu.
Client
(broker_url: str, queue_name: Optional[str] = None, conn_args: Optional[Dict[str, Any]] = None, exchange_name: Optional[str] = None, exchange_args: Optional[Dict[str, Any]] = None, routing_key: Optional[str] = None, result_queue_name: Optional[str] = None, result_queue_args: Optional[Dict[str, Any]] = 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 used - exchange_args – exchange arguments
- routing_key – reply message routing key. If
None
queue name is used - result_queue_name – result queue name. If
None
random exclusive queue is declared for each request - conn_args – additional connection arguments
- kwargs – parameters to be passed to
pjrpc.client.AbstractClient
-
close
() → None¶ Closes the current broker connection.
-
class
pjrpc.client.backend.aio_pika.
Client
(broker_url: str, queue_name: Optional[str] = None, conn_args: Optional[Dict[str, Any]] = None, exchange_name: Optional[str] = None, exchange_args: Optional[Dict[str, Any]] = None, routing_key: Optional[str] = None, result_queue_name: Optional[str] = None, result_queue_args: Optional[Dict[str, Any]] = 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 used - exchange_args – exchange arguments
- routing_key – reply message routing key. If
None
queue name is used - result_queue_name – result queue name. If
None
random exclusive queue is declared for each request - conn_args – additional connection arguments
- kwargs – parameters to be passed to
pjrpc.client.AbstractClient
-
close
() → None¶ Closes current broker connection.
-
connect
() → None¶ Opens a connection to the broker.
Tracer¶
-
class
pjrpc.client.tracer.
Tracer
¶ JSON-RPC client tracer.
-
on_request_begin
(trace_context: types.SimpleNamespace, request: pjrpc.common.v20.Request) → None¶ Handler called before JSON-RPC request begins.
Parameters: - trace_context – request trace context
- request – JSON-RPC request
-
on_request_end
(trace_context: types.SimpleNamespace, request: pjrpc.common.v20.Request, response: pjrpc.common.v20.Response) → None¶ Handler called after JSON-RPC request ends.
Parameters: - trace_context – request trace context
- request – JSON-RPC request
- response – JSON-RPC response
-
on_error
(trace_context: types.SimpleNamespace, request: Union[pjrpc.common.v20.Request, pjrpc.common.v20.BatchRequest], error: BaseException) → None¶ Handler called when JSON-RPC request failed.
Parameters: - trace_context – request trace context
- request – JSON-RPC request
- error – raised exception
-
-
class
pjrpc.client.tracer.
LoggingTracer
(logger: logging.Logger = <RootLogger root (WARNING)>, level: int = 10)¶ JSON-RPC client logging tracer.
-
on_request_begin
(trace_context: types.SimpleNamespace, request: pjrpc.common.v20.Request) → None¶ Handler called before JSON-RPC request begins.
Parameters: - trace_context – request trace context
- request – JSON-RPC request
-
on_request_end
(trace_context: types.SimpleNamespace, request: pjrpc.common.v20.Request, response: pjrpc.common.v20.Response) → None¶ Handler called after JSON-RPC request ends.
Parameters: - trace_context – request trace context
- request – JSON-RPC request
- response – JSON-RPC response
-
on_error
(trace_context: types.SimpleNamespace, request: Union[pjrpc.common.v20.Request, pjrpc.common.v20.BatchRequest], error: BaseException) → None¶ Handler called when JSON-RPC request failed.
Parameters: - trace_context – request trace context
- request – JSON-RPC request
- error – raised exception
-
Integrations¶
Server¶
JSON-RPC server package.
-
class
pjrpc.server.
AsyncDispatcher
(*, request_class: Type[pjrpc.common.v20.Request] = <class 'pjrpc.common.v20.Request'>, response_class: Type[pjrpc.common.v20.Response] = <class 'pjrpc.common.v20.Response'>, batch_request: Type[pjrpc.common.v20.BatchRequest] = <class 'pjrpc.common.v20.BatchRequest'>, batch_response: Type[pjrpc.common.v20.BatchResponse] = <class 'pjrpc.common.v20.BatchResponse'>, json_loader: Callable = <function loads>, json_dumper: Callable = <function dumps>, json_encoder: Type[pjrpc.server.dispatcher.JSONEncoder] = <class 'pjrpc.server.dispatcher.JSONEncoder'>, json_decoder: Optional[Type[json.decoder.JSONDecoder]] = None, middlewares: Iterable[Callable] = (), error_handlers: Dict[Union[None, int, Exception], List[Callable]] = {})¶ Asynchronous method dispatcher.
-
dispatch
(request_text: str, context: Optional[Any] = None) → Optional[str]¶ Deserializes request, dispatches it to the required method and serializes the result.
Parameters: - request_text – request text representation
- context – application context (if supported)
Returns: response text representation
-
-
class
pjrpc.server.
Dispatcher
(*, request_class: Type[pjrpc.common.v20.Request] = <class 'pjrpc.common.v20.Request'>, response_class: Type[pjrpc.common.v20.Response] = <class 'pjrpc.common.v20.Response'>, batch_request: Type[pjrpc.common.v20.BatchRequest] = <class 'pjrpc.common.v20.BatchRequest'>, batch_response: Type[pjrpc.common.v20.BatchResponse] = <class 'pjrpc.common.v20.BatchResponse'>, json_loader: Callable = <function loads>, json_dumper: Callable = <function dumps>, json_encoder: Type[pjrpc.server.dispatcher.JSONEncoder] = <class 'pjrpc.server.dispatcher.JSONEncoder'>, json_decoder: Optional[Type[json.decoder.JSONDecoder]] = None, middlewares: Iterable[Callable] = (), error_handlers: Dict[Union[None, int, Exception], List[Callable]] = {})¶ 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: Callable, name: Optional[str] = None, context: Optional[Any] = None) → None¶ Adds method to the registry.
Parameters: - method – method
- name – method name
- context – application context name
-
add_methods
(*methods) → None¶ Adds methods to the registry.
Parameters: methods – method list. Each method may be an instance of pjrpc.server.MethodRegistry
,pjrpc.server.Method
or plain function
-
view
(view: Type[pjrpc.server.dispatcher.ViewMixin]) → None¶ Adds class based view to the registry.
Parameters: view – view to be added
-
dispatch
(request_text: str, context: Optional[Any] = None) → Optional[str]¶ Deserializes request, dispatches it to the required method and serializes the result.
Parameters: - request_text – request text representation
- context – application context (if supported)
Returns: response text representation
-
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: Any) → Any¶ 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)
-
-
class
pjrpc.server.
Method
(method: Callable, name: Optional[str] = None, context: Optional[Any] = 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: Optional[str] = None)¶ Method registry.
Parameters: prefix – method name prefix to be used for naming containing methods -
get
(item: str) → Optional[pjrpc.server.dispatcher.Method]¶ Returns a method from the registry by name.
Parameters: item – method name Returns: found method or None
-
add
(maybe_method: Optional[Callable] = None, name: Optional[str] = None, context: Optional[Any] = None) → Callable¶ Decorator adding decorated method to the registry.
Parameters: - maybe_method – method or None
- name – method name to be used instead of __name__ attribute
- context – parameter name to be used as an application context
Returns: decorated method or decorator
-
add_methods
(*methods) → None¶ Adds methods to the registry.
Parameters: methods – methods to be added. Each one can be an instance of pjrpc.server.Method
or plain method
-
view
(maybe_view: Optional[Type[pjrpc.server.dispatcher.ViewMixin]] = None, context: Optional[Any] = None, prefix: Optional[str] = None) → Union[pjrpc.server.dispatcher.ViewMixin, Callable]¶ Methods view decorator.
Parameters: - maybe_view – view class instance or None
- context – application context name
- prefix – view methods prefix
Returns: decorator or decorated view
-
merge
(other: pjrpc.server.dispatcher.MethodRegistry) → None¶ Merges two registries.
Parameters: other – registry to be merged in the current one
-
-
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: str = '', spec: Optional[pjrpc.server.specs.Specification] = None, app: Optional[aiohttp.web_app.Application] = 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
-
app
¶ aiohttp application.
-
dispatcher
¶ JSON-RPC method dispatcher.
-
endpoints
¶ JSON-RPC application registered endpoints.
-
add_endpoint
(prefix: str, subapp: Optional[aiohttp.web_app.Application] = None, **kwargs) → pjrpc.server.dispatcher.Dispatcher¶ Adds additional endpoint.
Parameters: - prefix – endpoint prefix
- subapp – aiohttp subapp the endpoint will be served on
- kwargs – arguments to be passed to the dispatcher
pjrpc.server.Dispatcher
Returns: dispatcher
flask¶
Flask JSON-RPC extension.
-
class
pjrpc.server.integration.flask.
JsonRPC
(path: str, spec: Optional[pjrpc.server.specs.Specification] = 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
-
dispatcher
¶ JSON-RPC method dispatcher.
-
endpoints
¶ JSON-RPC application registered endpoints.
-
add_endpoint
(prefix: str, blueprint: Optional[flask.blueprints.Blueprint] = None, **kwargs) → pjrpc.server.dispatcher.Dispatcher¶ Adds additional endpoint.
Parameters: - prefix – endpoint prefix
- blueprint – flask blueprint the endpoint will be served on
- kwargs – arguments to be passed to the dispatcher
pjrpc.server.Dispatcher
Returns: dispatcher
-
init_app
(app: Union[flask.app.Flask, flask.blueprints.Blueprint]) → None¶ Initializes flask application with JSON-RPC extension.
Parameters: app – flask application instance
kombu¶
kombu JSON-RPC server integration.
-
class
pjrpc.server.integration.kombu.
Executor
(broker_url: str, queue_name: str, conn_args: Optional[Dict[str, Any]] = None, queue_args: Optional[Dict[str, Any]] = None, publish_args: Optional[Dict[str, Any]] = None, prefetch_count: int = 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
-
dispatcher
¶ JSON-RPC method dispatcher.
aio_pika¶
-
class
pjrpc.server.integration.aio_pika.
Executor
(broker_url: str, queue_name: str, prefetch_count: int = 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
-
dispatcher
¶ JSON-RPC method dispatcher.
-
shutdown
() → None¶ Stops executor.
-
start
(queue_args: Optional[Dict[str, Any]] = None) → None¶ Starts executor.
Parameters: queue_args – queue arguments
werkzeug¶
-
class
pjrpc.server.integration.werkzeug.
JsonRPC
(path: str = '', **kwargs)¶ werkzeug server JSON-RPC integration.
Parameters: - path – JSON-RPC handler base path
- kwargs – arguments to be passed to the dispatcher
pjrpc.server.Dispatcher
-
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: Optional[Callable] = None, **kwargs) → Callable¶ Decorator marks a method the parameters of which to be validated when calling it using JSON-RPC protocol.
Parameters: - maybe_method – method the parameters of which to be validated or
None
if called as @validate(…) - kwargs – validator arguments
- maybe_method – method the parameters of which to be validated or
-
validate_method
(method: Callable, params: Union[list, dict, None], exclude: Iterable[str] = (), **kwargs) → Dict[str, Any]¶ Validates params against method signature.
Parameters: - method – method to validate parameters against
- params – parameters to be validated
- exclude – parameter names to be excluded from validation
- kwargs – additional validator arguments
Raises: Returns: bound method parameters
-
bind
(signature: inspect.Signature, params: Union[list, dict, None]) → inspect.BoundArguments¶ 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
-
signature
¶ Returns method signature.
Parameters: - method – method to get signature of
- exclude – parameters to be excluded
Returns: signature
-
-
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 -
validate_method
(method: Callable, params: Union[list, dict, None], exclude: Iterable[str] = (), **kwargs) → Dict[str, Any]¶ Validates params against method using
pydantic
validator.Parameters: - method – method to validate parameters against
- params – parameters to be validated
- exclude – parameter names to be excluded from validation
- kwargs – jsonschema validator arguments
Raises:
-
pydantic¶
-
class
pjrpc.server.validators.pydantic.
PydanticValidator
(coerce: bool = 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: Callable, params: Union[list, dict, None], exclude: Iterable[str] = (), **kwargs) → Dict[str, Any]¶ Validates params against method using
pydantic
validator.Parameters: - method – method to validate parameters against
- params – parameters to be validated
- exclude – parameter names to be excluded from validation
Returns: coerced parameters if coerce flag is
True
otherwise parameters as isRaises: ValidationError
-
build_validation_schema
¶ Builds pydantic model based validation schema from method signature.
Parameters: signature – method signature to build schema for Returns: validation schema
-
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: Any) → Any¶ 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)
-
-
class
pjrpc.server.specs.
BaseUI
¶ Base UI.
-
get_static_folder
() → str¶ Returns ui statics folder.
-
get_index_page
(spec_url: str) → str¶ Returns ui index webpage.
Parameters: spec_url – specification url.
-
-
class
pjrpc.server.specs.
Specification
(path: str = '/spec.json', ui: Optional[pjrpc.server.specs.BaseUI] = None, ui_path: Optional[str] = None)¶ JSON-RPC specification.
Parameters: - path – specification url path suffix
- ui – specification ui instance
- ui_path – specification ui url path suffix
-
path
¶ Returns specification url path.
-
ui
¶ Returns ui instance.
-
ui_path
¶ Returns specification ui url path.
-
schema
(path: str, methods: Iterable[pjrpc.server.dispatcher.Method] = (), methods_map: Dict[str, Iterable[pjrpc.server.dispatcher.Method]] = {}) → dict¶ Returns specification schema.
Parameters: - path – methods endpoint path
- methods – methods list the specification is generated for
- methods_map – methods map the specification is generated for. Each item is a mapping from a prefix to methods on which the methods will be served
extractors¶
-
class
pjrpc.server.specs.extractors.
Schema
(schema: Dict[str, Any], required: bool = True, summary: str = UNSET, description: str = UNSET, deprecated: bool = UNSET, definitions: Dict[str, Any] = UNSET)¶ Method parameter/result schema.
-
class
pjrpc.server.specs.extractors.
Example
(params: Dict[str, Any], result: Any, version: str = '2.0', summary: str = UNSET, description: str = UNSET)¶ Method usage example.
-
class
pjrpc.server.specs.extractors.
Tag
(name: str, description: str = UNSET, externalDocs: str = UNSET)¶ A list of method tags.
-
class
pjrpc.server.specs.extractors.
Error
(code: int, message: str, data: Dict[str, Any] = UNSET)¶ Defines an application level error.
-
class
pjrpc.server.specs.extractors.
BaseSchemaExtractor
¶ Base method schema extractor.
-
extract_params_schema
(method: Callable, exclude: Iterable[str] = ()) → Dict[str, pjrpc.server.specs.extractors.Schema]¶ Extracts method parameters schema.
-
extract_result_schema
(method: Callable) → pjrpc.server.specs.extractors.Schema¶ Extracts method result schema.
-
extract_description
(method: Callable) → Union[pjrpc.common.common.UnsetType, str]¶ Extracts method description.
-
extract_summary
(method: Callable) → Union[pjrpc.common.common.UnsetType, str]¶ Extracts method summary.
-
extract_errors_schema
(method: Callable) → Union[pjrpc.common.common.UnsetType, List[pjrpc.server.specs.extractors.Error]]¶ Extracts method errors schema.
Extracts method tags.
-
extract_examples
(method: Callable) → Union[pjrpc.common.common.UnsetType, List[pjrpc.server.specs.extractors.Example]]¶ Extracts method usage examples.
-
extract_deprecation_status
(method: Callable) → Union[pjrpc.common.common.UnsetType, bool]¶ Extracts method deprecation status.
-
-
class
pjrpc.server.specs.extractors.pydantic.
PydanticSchemaExtractor
(ref_template: str = '#/components/schemas/{model}')¶ Pydantic method specification extractor.
-
extract_params_schema
(method: Callable, exclude: Iterable[str] = ()) → Dict[str, pjrpc.server.specs.extractors.Schema]¶ Extracts method parameters schema.
-
extract_result_schema
(method: Callable) → pjrpc.server.specs.extractors.Schema¶ Extracts method result schema.
-
schemas¶
OpenAPI Specification generator. See https://swagger.io/specification/.
-
class
pjrpc.server.specs.openapi.
Contact
(name: str = UNSET, url: str = UNSET, email: str = 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: str, url: str = 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: str, version: str, description: str = UNSET, contact: pjrpc.server.specs.openapi.Contact = UNSET, license: pjrpc.server.specs.openapi.License = UNSET, termsOfService: str = 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: str, enum: List[str] = UNSET, description: str = 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: str, description: str = UNSET, variables: Dict[str, pjrpc.server.specs.openapi.ServerVariable] = 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: str, description: str = 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: str, description: str = UNSET, externalDocs: pjrpc.server.specs.openapi.ExternalDocumentation = 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
¶ The type of the security scheme.
-
APIKEY
= 'apiKey'¶
-
HTTP
= 'http'¶
-
OAUTH2
= 'oauth2'¶
-
OPENID_CONNECT
= 'openIdConnect'¶
-
-
class
pjrpc.server.specs.openapi.
ApiKeyLocation
¶ The location of the API key.
-
QUERY
= 'query'¶
-
HEADER
= 'header'¶
-
COOKIE
= 'cookie'¶
-
-
class
pjrpc.server.specs.openapi.
OAuthFlow
(authorizationUrl: str, tokenUrl: str, scopes: Dict[str, str], refreshUrl: str = 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: pjrpc.server.specs.openapi.OAuthFlow = UNSET, password: pjrpc.server.specs.openapi.OAuthFlow = UNSET, clientCredentials: pjrpc.server.specs.openapi.OAuthFlow = UNSET, authorizationCode: pjrpc.server.specs.openapi.OAuthFlow = 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: pjrpc.server.specs.openapi.SecuritySchemeType, scheme: str, name: str = UNSET, location: pjrpc.server.specs.openapi.ApiKeyLocation = UNSET, bearerFormat: str = UNSET, flows: pjrpc.server.specs.openapi.OAuthFlows = UNSET, openIdConnectUrl: str = UNSET, description: str = 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: Dict[str, pjrpc.server.specs.openapi.SecurityScheme] = UNSET, schemas: Dict[str, Dict[str, Any]] = <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: int, message: str, data: Dict[str, Any] = 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: Dict[str, Any], result: Any, version: str = '2.0', summary: str = UNSET, description: str = 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: Any, summary: str = UNSET, description: str = UNSET, externalValue: str = 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: Dict[str, Any], examples: Dict[str, pjrpc.server.specs.openapi.ExampleObject] = 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: str, content: Dict[str, pjrpc.server.specs.openapi.MediaType] = 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: Dict[str, pjrpc.server.specs.openapi.MediaType], required: bool = UNSET, description: str = 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
¶ The location of the parameter.
-
QUERY
= 'query'¶
-
HEADER
= 'header'¶
-
PATH
= 'path'¶
-
COOKIE
= 'cookie'¶
-
-
class
pjrpc.server.specs.openapi.
StyleType
¶ 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: str, location: pjrpc.server.specs.openapi.ParameterLocation, description: str = UNSET, required: bool = UNSET, deprecated: bool = UNSET, allowEmptyValue: bool = UNSET, style: pjrpc.server.specs.openapi.StyleType = UNSET, explode: bool = UNSET, allowReserved: bool = UNSET, schema: Dict[str, Any] = UNSET, examples: Dict[str, pjrpc.server.specs.openapi.ExampleObject] = UNSET, content: Dict[str, pjrpc.server.specs.openapi.MediaType] = 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: Dict[str, pjrpc.server.specs.openapi.Response], requestBody: pjrpc.server.specs.openapi.RequestBody = UNSET, tags: List[str] = UNSET, summary: str = UNSET, description: str = UNSET, externalDocs: pjrpc.server.specs.openapi.ExternalDocumentation = UNSET, deprecated: bool = UNSET, servers: List[pjrpc.server.specs.openapi.Server] = UNSET, security: List[Dict[str, List[str]]] = UNSET, parameters: List[pjrpc.server.specs.openapi.Parameter] = 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: pjrpc.server.specs.openapi.Operation = UNSET, put: pjrpc.server.specs.openapi.Operation = UNSET, post: pjrpc.server.specs.openapi.Operation = UNSET, delete: pjrpc.server.specs.openapi.Operation = UNSET, options: pjrpc.server.specs.openapi.Operation = UNSET, head: pjrpc.server.specs.openapi.Operation = UNSET, patch: pjrpc.server.specs.openapi.Operation = UNSET, trace: pjrpc.server.specs.openapi.Operation = UNSET, summary: str = UNSET, description: str = UNSET, servers: List[pjrpc.server.specs.openapi.Server] = 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: Dict[str, pjrpc.server.specs.extractors.Schema] = UNSET, result_schema: pjrpc.server.specs.extractors.Schema = UNSET, errors: List[Union[pjrpc.server.specs.openapi.Error, Type[pjrpc.common.exceptions.JsonRpcError]]] = UNSET, examples: List[pjrpc.server.specs.openapi.MethodExample] = UNSET, tags: List[str] = UNSET, summary: str = UNSET, description: str = UNSET, external_docs: pjrpc.server.specs.openapi.ExternalDocumentation = UNSET, deprecated: bool = UNSET, security: List[Dict[str, List[str]]] = UNSET, parameters: List[pjrpc.server.specs.openapi.Parameter] = UNSET)¶ Adds Open Api specification annotation to the method.
Parameters: - params_schema – method parameters JSON schema
- result_schema – method result JSON schema
- errors – method errors
- examples – method usage examples
- tags – a list of tags for method documentation control
- summary – a short summary of what the method does
- description – a verbose explanation of the method behavior
- external_docs – an external resource for extended documentation
- deprecated – declares this method to be deprecated
- security – a declaration of which security mechanisms can be used for the method
- parameters – a list of parameters that are applicable for the method
-
class
pjrpc.server.specs.openapi.
OpenAPI
(info: pjrpc.server.specs.openapi.Info, path: str = '/openapi.json', servers: List[pjrpc.server.specs.openapi.Server] = UNSET, external_docs: Optional[pjrpc.server.specs.openapi.ExternalDocumentation] = UNSET, tags: List[pjrpc.server.specs.openapi.Tag] = UNSET, security: List[Dict[str, List[str]]] = UNSET, security_schemes: Dict[str, pjrpc.server.specs.openapi.SecurityScheme] = UNSET, openapi: str = '3.0.0', schema_extractor: Optional[pjrpc.server.specs.extractors.BaseSchemaExtractor] = None, ui: Optional[pjrpc.server.specs.BaseUI] = None, ui_path: str = '/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: str, methods: Iterable[pjrpc.server.dispatcher.Method] = (), methods_map: Dict[str, Iterable[pjrpc.server.dispatcher.Method]] = {}) → dict¶ Returns specification schema.
Parameters: - path – methods endpoint path
- methods – methods list the specification is generated for
- methods_map – methods map the specification is generated for. Each item is a mapping from a prefix to methods on which the methods will be served
-
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). -
get_static_folder
() → str¶ Returns ui statics folder.
-
-
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) -
get_static_folder
() → str¶ Returns ui statics folder.
-
-
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) -
get_static_folder
() → str¶ Returns ui statics folder.
-
OpenRPC specification generator. See https://spec.open-rpc.org/.
-
class
pjrpc.server.specs.openrpc.
Contact
(name: str = UNSET, url: str = UNSET, email: str = 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: str, url: str = 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: str, version: str, description: str = UNSET, contact: pjrpc.server.specs.openrpc.Contact = UNSET, license: pjrpc.server.specs.openrpc.License = UNSET, termsOfService: str = 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: str, url: str, summary: str = UNSET, description: str = 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: str, description: str = 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: str, summary: str = UNSET, description: str = UNSET, externalDocs: pjrpc.server.specs.openrpc.ExternalDocumentation = 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: Union[str, int, float, dict, bool, list, tuple, set, None], name: str, summary: str = UNSET, description: str = 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: str, params: List[pjrpc.server.specs.openrpc.ExampleObject], result: pjrpc.server.specs.openrpc.ExampleObject, summary: str = UNSET, description: str = 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: str, schema: Dict[str, Any], summary: str = UNSET, description: str = UNSET, required: bool = UNSET, deprecated: bool = 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: int, message: str, data: Dict[str, Any] = 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
¶ The expected format of the parameters.
-
BY_NAME
= 'by-name'¶
-
BY_POSITION
= 'by-position'¶
-
EITHER
= 'either'¶
-
-
class
pjrpc.server.specs.openrpc.
MethodInfo
(name: str, params: List[Union[pjrpc.server.specs.openrpc.ContentDescriptor, dict]], result: Union[pjrpc.server.specs.openrpc.ContentDescriptor, dict], errors: List[pjrpc.server.specs.openrpc.Error] = UNSET, paramStructure: pjrpc.server.specs.openrpc.ParamStructure = UNSET, examples: List[pjrpc.server.specs.openrpc.MethodExample] = UNSET, summary: str = UNSET, description: str = UNSET, tags: List[pjrpc.server.specs.openrpc.Tag] = UNSET, deprecated: bool = UNSET, externalDocs: pjrpc.server.specs.openrpc.ExternalDocumentation = UNSET, servers: List[pjrpc.server.specs.openrpc.Server] = 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: Dict[str, Any] = <factory>)¶ Set of reusable objects for different aspects of the OpenRPC.
Parameters: schemas – reusable Schema Objects
-
pjrpc.server.specs.openrpc.
annotate
(params_schema: List[pjrpc.server.specs.openrpc.ContentDescriptor] = UNSET, result_schema: pjrpc.server.specs.openrpc.ContentDescriptor = UNSET, errors: List[Union[pjrpc.server.specs.openrpc.Error, Type[pjrpc.common.exceptions.JsonRpcError]]] = UNSET, examples: List[pjrpc.server.specs.openrpc.MethodExample] = UNSET, summary: str = UNSET, description: str = UNSET, tags: List[Union[pjrpc.server.specs.openrpc.Tag, str]] = UNSET, deprecated: bool = UNSET)¶ Adds JSON-RPC method to the API specification.
Parameters: - params_schema – a list of parameters that are applicable for this method
- result_schema – the description of the result returned by the method
- errors – a list of custom application defined errors that MAY be returned
- examples – method usage example
- 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
-
class
pjrpc.server.specs.openrpc.
OpenRPC
(info: pjrpc.server.specs.openrpc.Info, path: str = '/openrpc.json', servers: List[pjrpc.server.specs.openrpc.Server] = UNSET, external_docs: Optional[pjrpc.server.specs.openrpc.ExternalDocumentation] = UNSET, openrpc: str = '1.0.0', schema_extractor: Optional[pjrpc.server.specs.extractors.BaseSchemaExtractor] = 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: str, methods: Iterable[pjrpc.server.dispatcher.Method] = (), methods_map: Dict[str, Iterable[pjrpc.server.dispatcher.Method]] = {}) → dict¶ Returns specification schema.
Parameters: - path – methods endpoint path
- methods – methods list the specification is generated for
- methods_map – methods map the specification is generated for. Each item is a mapping from a prefix to methods on which the methods will be served