API reference¶
This page is generated from the docstrings in the source code, so it matches the code on the main branch.
Everything in the first four sections can be imported from the package
itself, for example from jsonrpcclient import request, parse. The other
public names are in jsonrpcclient.id_generators, jsonrpcclient.utils,
jsonrpcclient.responses (the Response type) and jsonrpcclient.requests
(the Params type). Anything not listed here is internal and can change in
any release.
In the signatures, id=NOID means "no id given": the request takes the next
id from its sequence.
Requests¶
request
¶
request(method: str, params: Optional[Params] = None, id: Any = NOID) -> Dict[str, Any]
Build a request with an id.
Unless you pass id, ids count up from 1. The sequence is shared by the
whole process and is safe to use from several threads.
Parameters:
-
method(str) –The name of the method to call.
-
params(Optional[Params], default:None) –Positional params as a list or tuple, or named params as a dict. Left out of the request if empty or not given. Only the type hint restricts it; nothing is checked at runtime.
-
id(Any, default:NOID) –The id to use instead of the next one in the sequence. Any JSON value works.
id=Nonesends"id": null; it does not make a notification (usenotificationfor that).
Returns:
-
Dict[str, Any]–The request as a dict, ready to serialize. Tuple params are converted to a list.
Examples:
>>> request("sqrt", [16], id=1)
{'jsonrpc': '2.0', 'method': 'sqrt', 'params': [16], 'id': 1}
>>> request("greet", {"name": "Ada"}, id="abc")
{'jsonrpc': '2.0', 'method': 'greet', 'params': {'name': 'Ada'}, 'id': 'abc'}
request_hex
¶
request_hex(method: str, params: Optional[Params] = None, id: Any = NOID) -> Dict[str, Any]
Build a request whose ids count up in hexadecimal strings: "1", ... "9", "a".
The hex sequence is separate from the one request uses.
Parameters:
-
method(str) –The name of the method to call.
-
params(Optional[Params], default:None) –Positional params as a list or tuple, or named params as a dict. Left out of the request if empty or not given.
-
id(Any, default:NOID) –The id to use instead of the next one in the sequence.
Returns:
-
Dict[str, Any]–The request as a dict, ready to serialize.
request_random
¶
request_random(method: str, params: Optional[Params] = None, id: Any = NOID) -> Dict[str, Any]
Build a request whose id is a random string of 8 lowercase letters and digits.
Random ids are not guaranteed to be unique; use request_uuid if a clash
would matter.
Parameters:
-
method(str) –The name of the method to call.
-
params(Optional[Params], default:None) –Positional params as a list or tuple, or named params as a dict. Left out of the request if empty or not given.
-
id(Any, default:NOID) –The id to use instead of the next one in the sequence.
Returns:
-
Dict[str, Any]–The request as a dict, ready to serialize.
request_uuid
¶
request_uuid(method: str, params: Optional[Params] = None, id: Any = NOID) -> Dict[str, Any]
Build a request whose id is a random UUID (version 4) string.
Use this when several processes or machines send requests to the same server.
Parameters:
-
method(str) –The name of the method to call.
-
params(Optional[Params], default:None) –Positional params as a list or tuple, or named params as a dict. Left out of the request if empty or not given.
-
id(Any, default:NOID) –The id to use instead of the next one in the sequence.
Returns:
-
Dict[str, Any]–The request as a dict, ready to serialize.
request_json
¶
request_json(method: str, params: Optional[Params] = None, id: Any = NOID) -> str
Build a request as a JSON string.
The same as json.dumps(request(method, params, id)), and it takes the next
id from the same sequence as request.
Parameters:
-
method(str) –The name of the method to call.
-
params(Optional[Params], default:None) –Positional params as a list or tuple, or named params as a dict.
-
id(Any, default:NOID) –The id to use instead of the next one in the sequence.
Returns:
-
str–The request serialized with
json.dumps.
Raises:
-
TypeError–If
paramsoridholds somethingjson.dumpscan't serialize.
Examples:
>>> request_json("ping", id=1)
'{"jsonrpc": "2.0", "method": "ping", "id": 1}'
request_json_hex
¶
request_json_hex(method: str, params: Optional[Params] = None, id: Any = NOID) -> str
Build a request with a hexadecimal id, as a JSON string.
The same as json.dumps(request_hex(method, params, id)).
Parameters:
-
method(str) –The name of the method to call.
-
params(Optional[Params], default:None) –Positional params as a list or tuple, or named params as a dict. Left out of the request if empty or not given.
-
id(Any, default:NOID) –The id to use instead of the next one in the sequence.
Returns:
-
str–The request serialized with
json.dumps.
Raises:
-
TypeError–If
paramsoridholds somethingjson.dumpscan't serialize.
request_json_random
¶
request_json_random(method: str, params: Optional[Params] = None, id: Any = NOID) -> str
Build a request with a random id, as a JSON string.
The same as json.dumps(request_random(method, params, id)).
Parameters:
-
method(str) –The name of the method to call.
-
params(Optional[Params], default:None) –Positional params as a list or tuple, or named params as a dict. Left out of the request if empty or not given.
-
id(Any, default:NOID) –The id to use instead of the next one in the sequence.
Returns:
-
str–The request serialized with
json.dumps.
Raises:
-
TypeError–If
paramsoridholds somethingjson.dumpscan't serialize.
request_json_uuid
¶
request_json_uuid(method: str, params: Optional[Params] = None, id: Any = NOID) -> str
Build a request with a UUID id, as a JSON string.
The same as json.dumps(request_uuid(method, params, id)).
Parameters:
-
method(str) –The name of the method to call.
-
params(Optional[Params], default:None) –Positional params as a list or tuple, or named params as a dict. Left out of the request if empty or not given.
-
id(Any, default:NOID) –The id to use instead of the next one in the sequence.
Returns:
-
str–The request serialized with
json.dumps.
Raises:
-
TypeError–If
paramsoridholds somethingjson.dumpscan't serialize.
Notifications¶
notification
¶
notification(method: str, params: Optional[Params] = None) -> Dict[str, Any]
Build a notification: a request with no id, which the server doesn't answer.
Parameters:
-
method(str) –The name of the method to call.
-
params(Optional[Params], default:None) –Positional params as a list or tuple, or named params as a dict. Left out of the notification if empty or not given.
Returns:
-
Dict[str, Any]–The notification as a dict, ready to serialize. Tuple params are converted to a list.
Examples:
>>> notification("log", ["hello"])
{'jsonrpc': '2.0', 'method': 'log', 'params': ['hello']}
notification_json
¶
notification_json(method: str, params: Optional[Params] = None) -> str
Build a notification as a JSON string.
The same as json.dumps(notification(method, params)).
Parameters:
-
method(str) –The name of the method to call.
-
params(Optional[Params], default:None) –Positional params as a list or tuple, or named params as a dict.
Returns:
-
str–The notification serialized with
json.dumps.
Raises:
-
TypeError–If
paramsholds somethingjson.dumpscan't serialize.
Examples:
>>> notification_json("log", ["hello"])
'{"jsonrpc": "2.0", "method": "log", "params": ["hello"]}'
Responses¶
parse
¶
parse(deserialized: Dict[str, Any]) -> Response
parse(deserialized: List[Dict[str, Any]]) -> Iterator[Response]
Parse a deserialized response, or a batch of them.
A dict gives one Ok or Error. A list (a batch) gives a lazy iterator of
Ok and Error: each item is parsed when you reach it, and the iterator
can only be used once. Call list() on it if you need the responses more
than once. Batch responses can come back in any order, so match them up by
id.
If a response has a non-null error, it is an Error, even if it also has
a result.
Parameters:
-
deserialized(Deserialized) –A response that has already been through
json.loads(or your HTTP library's.json()).
Returns:
Raises:
-
InvalidResponse–If a response is malformed. For a batch, this happens when the iterator reaches the bad item. Subclasses
KeyErrorandTypeError. -
TypeError–If
deserializedis astr,bytesorbytearray. Useparse_jsonfor those.
Examples:
>>> parse({"jsonrpc": "2.0", "result": "pong", "id": 1})
Ok(result='pong', id=1)
>>> list(parse([{"jsonrpc": "2.0", "result": "pong", "id": 1}]))
[Ok(result='pong', id=1)]
parse_json
¶
parse_json(response: Union[str, bytes, bytearray], **kwargs: Any) -> Union[Response, Iterator[Response]]
Parse a response, or a batch of them, from a JSON string.
The same as parse(json.loads(response, **kwargs)), except that it doesn't
raise TypeError for a string.
Parameters:
-
response(Union[str, bytes, bytearray]) –The response body, as
str,bytesorbytearray. -
**kwargs(Any, default:{}) –Passed to
json.loads, for exampleparse_float=Decimal.
Returns:
-
Union[Response, Iterator[Response]]–An
OkorErrorfor a JSON object, or an iterator of them for a JSON array.
Raises:
-
ValueError–If
responseisn't valid JSON. Usually this isjson.JSONDecodeError, orUnicodeDecodeErrorfor bytes that aren't valid UTF-8. -
InvalidResponse–If a response is malformed, including JSON that is neither an object nor an array.
Examples:
>>> parse_json('{"jsonrpc": "2.0", "result": "pong", "id": 1}')
Ok(result='pong', id=1)
Ok
¶
Bases: NamedTuple
A successful response.
A named tuple, so it also unpacks as result, id = parsed.
Examples:
>>> parse({"jsonrpc": "2.0", "result": "pong", "id": 1})
Ok(result='pong', id=1)
Error
¶
Bases: NamedTuple
An error response.
A named tuple of the members of the response's error object plus the id.
The library doesn't check the types of code and message; they are
whatever the server sent.
Examples:
>>> error = {"code": -32601, "message": "Method not found"}
>>> parse({"jsonrpc": "2.0", "error": error, "id": 1})
Error(code=-32601, message='Method not found', data=None, id=1)
Exceptions¶
InvalidResponse
¶
Bases: KeyError, TypeError
Raised when a response isn't a valid JSON-RPC 2.0 response.
The message says what is wrong, for example
Invalid JSON-RPC response: missing 'id'.
It subclasses KeyError and TypeError because versions before 4.1.0
raised one of those for a malformed response, so except KeyError and
except TypeError still catch it.
Added in 4.1.0.
Id generators¶
Iterators of request ids.
Each function returns a new, independent iterator. Take ids from it with
next() and pass them to request(..., id=...). Every iterator is safe to
share between threads.
The request, request_hex, request_random and request_uuid functions
each use their own module-level iterator from here, shared by the whole
process.
decimal
¶
decimal(start: int = 1) -> Iterator[int]
Count up in integers: 1, 2, 3, and so on.
Parameters:
-
start(int, default:1) –The first id.
Returns:
-
Iterator[int]–An endless, thread-safe iterator of ints.
Examples:
>>> ids = decimal(100)
>>> next(ids), next(ids)
(100, 101)
hexadecimal
¶
hexadecimal(start: int = 1) -> Iterator[str]
Count up in lowercase hexadecimal strings: "1", ... "9", "a", "b".
Parameters:
-
start(int, default:1) –The first id, as an int.
hexadecimal(10)starts at "a".
Returns:
-
Iterator[str]–An endless, thread-safe iterator of strs.
Examples:
>>> ids = hexadecimal(9)
>>> next(ids), next(ids)
('9', 'a')
random
¶
random(length: int = 8, chars: str = digits + ascii_lowercase) -> Iterator[str]
Random strings, such as "fubui5e6".
The ids are not guaranteed to be unique, and Python's random.choice
is not a secure source of randomness. With the defaults there are 36**8
(about 2.8 million million) possible ids, so a clash between two ids in
flight at the same time is very unlikely. Use uuid if a clash would
matter.
Parameters:
-
length(int, default:8) –The number of characters in each id.
-
chars(str, default:digits + ascii_lowercase) –The characters to choose from. The default is the digits and the lowercase letters a to z.
Returns:
-
Iterator[str]–An endless, thread-safe iterator of strs.
Examples:
>>> len(next(random(length=12)))
12
uuid
¶
uuid() -> Iterator[str]
Random UUIDs (version 4) as strings.
For example "9bfe2c93-717e-4a45-b91b-55422c5af4ff". The safe choice when several processes or machines send requests to the same server.
Returns:
-
Iterator[str]–An endless, thread-safe iterator of strs.
Types¶
Response
module-attribute
¶
The type of one parsed response. Use it to annotate your own functions.
Params
module-attribute
¶
Params = Union[Dict[str, Any], List[Any], Tuple[Any, ...]]
The type of params: a list or tuple for positional params, a dict for named.
A tuple is sent as a list. Empty params are left out of the request.
Utilities¶
compose
¶
compose(*funcs: Callable[..., Any]) -> Callable[..., Any]
Combine functions into one that applies them from right to left.
compose(f, g)(x) is f(g(x)). The last function gets all the arguments;
each one before it gets the previous one's return value. The FAQ uses it to
build request_json and parse_json with another JSON library.
Parameters:
-
*funcs(Callable[..., Any], default:()) –Two or more functions. With one function, that function is returned unchanged.
Returns:
-
Callable[..., Any]–The composed function.
Raises:
-
TypeError–If no functions are given.
Examples:
>>> import json
>>> from jsonrpcclient import request
>>> to_json = compose(json.dumps, request)
>>> to_json("ping", id=1)
'{"jsonrpc": "2.0", "method": "ping", "id": 1}'
Version¶
__version__
module-attribute
¶
__version__ = '4.1.0'
The version of jsonrpcclient, as a string. Added in 4.0.4.