Skip to main content

JSON-RPC 2.0 client library for Python 3

Project description

A JSON-RPC 2.0 client library for Python 3.

To make a remote procedure call:

  1. Set the server address

  2. Use request() to call the remote method

>>> import jsonrpcclient
>>> server = jsonrpcclient.Server('http://endpoint/')
>>> server.request('add', 2, 3)
--> {"jsonrpc": "2.0", "method": "add", "params": [2, 3], "id": 1}
<-- {"jsonrpc": "2.0", "result": 5, "id": 1}
5

The first argument to request() is the method name; everything else is passed as parameters. You can pass any number of positional or keyword arguments, and they will be translated into JSON-RPC.

>>> result = server.request('find', 42, name='Foo')
--> {"jsonrpc": "2.0", "method": "find", "params": [42, {"name": "Foo"}], "id": 1}
<-- {"jsonrpc": "2.0", "result": "Bar", "id": 1}
Bar

If you don’t need any data returned, use notify() instead:

>>> server.notify('go')
--> {"jsonrpc": "2.0", "method": "go"}
<-- 200 OK

Shorthand

There’s another way to send messages:

>>> server.add(2, 3, response=True)
--> {"jsonrpc": "2.0", "method": "add", "params": [2, 3], "id": 1}
<-- {"jsonrpc": "2.0", "result": 5, "id": 1}
5

The library catches the undefined add() call, and sends it as a JSON-RPC message.

response=True tells the server you’re expecting a response; without that it’s a notification.

Exceptions

You should catch RPCClientException. This will be raised in the event of connection problems, or if the server responded with a JSON-RPC error response.

try:
    server.go()
except jsonrpcclient.exceptions.RPCClientException as e:
    print(str(e))

Logging

If you don’t want to see the underlying JSON messages, increase the logging level above DEBUG:

logging.getLogger('jsonrpcclient').setLevel(logging.INFO)

If you need a server, try my jsonrpcserver library.

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

jsonrpcclient-1.0.4.tar.gz (5.5 kB view details)

Uploaded Source

File details

Details for the file jsonrpcclient-1.0.4.tar.gz.

File metadata

File hashes

Hashes for jsonrpcclient-1.0.4.tar.gz
Algorithm Hash digest
SHA256 32441125e40fafab813d6dc220698ae64d24fbf1b3a95553456dea9fc0052211
MD5 3972a4bd5b0977a1363fd1e428d5ae4b
BLAKE2b-256 4c341d3c958a542fdf67e0fc2abf03bcad4b25487cb9a9a1b864a2d8cd45035e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page