JSON-RPC Client

4.0.3 · active · verified Thu Apr 16

jsonrpcclient is a Python library for generating JSON-RPC requests and parsing responses according to the JSON-RPC 2.0 specification. It is designed to be transport-agnostic, focusing solely on the protocol messaging rather than the underlying communication method. The current version is 4.0.3, released on February 23, 2023, and the library appears to be actively maintained with periodic updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to construct a JSON-RPC request and parse a response using `jsonrpcclient`. It illustrates the library's core functionality for message handling, assuming an external library like `requests` is used for network transport.

import requests
import json
from jsonrpcclient import request, parse

# Define a mock JSON-RPC server URL for demonstration. Replace with your actual endpoint.
# For a real server, ensure it's running and accessible.
# Example: A simple server might expose a 'subtract' method.
jsonrpc_server_url = "http://localhost:5000/jsonrpc"

# 1. Create a JSON-RPC request (Python dictionary-like object)
# This example requests the 'subtract' method with positional parameters and an ID.
request_obj = request("subtract", params=[42, 23], id=1)
print(f"Generated JSON-RPC Request: {json.dumps(request_obj, indent=2)}")

# 2. Send the request using a transport layer (e.g., 'requests' for HTTP)
try:
    # In a real application, you would send request_obj to your server
    # and get a response_data from it. Example using 'requests' library:
    # response_obj_from_server = requests.post(jsonrpc_server_url, json=request_obj).json()

    # For quickstart, simulate a successful response from a server
    response_obj_from_server = {"jsonrpc": "2.0", "result": 19, "id": 1}

    print(f"\nReceived JSON-RPC Response Object: {json.dumps(response_obj_from_server, indent=2)}")

    # 3. Parse the received response
    parsed_response = parse(response_obj_from_server)

    # 4. Handle the parsed response
    if parsed_response.ok:
        print(f"\nSuccessfully Parsed Result: {parsed_response.result}")
    else:
        print(f"\nError Received from Server (Code: {parsed_response.error.code}): {parsed_response.error.message}")
        if parsed_response.error.data:
            print(f"  Error Data: {parsed_response.error.data}")

except requests.exceptions.ConnectionError:
    print(f"\nError: Could not connect to the JSON-RPC server at {jsonrpc_server_url}. Please ensure the server is running.")
except json.JSONDecodeError:
    print("\nError: Failed to decode JSON response from the server.")
except Exception as e:
    print(f"\nAn unexpected error occurred: {e}")

view raw JSON →