Install & Compatibility
Where this runs
tested against v1.15.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.940 runs
installs and imports cleanly · install 0.0s · import 0.062s · 20.1MB
glibcpy 3.10–3.940 runs
installs and imports cleanly · install 1.7s · import 0.058s · 21MB
18MB installed
● package 18MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
JSONRPCResponseManager
✓ from jsonrpc.manager import JSONRPCResponseManager
JSONRPCClient
✓ from jsonrpc.client import JSONRPCClient
jsonrpc
✓ import jsonrpc
✗ import json_rpc
The package is installed as `json-rpc` but imported as `jsonrpc`.
This quickstart demonstrates the core functionality of `json-rpc`: how `JSONRPCResponseManager` dispatches incoming JSON-RPC requests on the server side and how `JSONRPCClient` constructs outgoing requests. It includes examples of successful calls, parameter passing, and error handling. Note that the actual network transport (e.g., HTTP POST) needs to be implemented separately, often using libraries like `requests` for clients or `werkzeug`/Flask for servers.
import json
import os
from jsonrpc.manager import JSONRPCResponseManager
from jsonrpc.client import JSONRPCClient
# --- Server-side logic (how to handle an incoming JSON-RPC request) ---
def add(a, b):
return a + b
def greet(name="Guest"):
return f"Hello, {name}!"
def secure_data(token):
# Simulate an authentication check using an environment variable
expected_token = os.environ.get('AUTH_TOKEN', 'super_secret_token_123')
if token == expected_token:
return "Sensitive data accessed."
else:
# JSON-RPC error response is automatically handled by the manager
raise ValueError("Invalid token")
# Define a dispatcher mapping method names to Python functions
dispatcher = {
"add": add,
"greet": greet,
"secure_data": secure_data,
}
# Simulate an incoming raw JSON-RPC request string
incoming_request_str = json.dumps({
"jsonrpc": "2.0",
"method": "add",
"params": {"a": 5, "b": 3},
"id": "req-123"
})
# Process the request using the manager
print("--- Server processing request ---")
response_object = JSONRPCResponseManager.handle(incoming_request_str, dispatcher)
if response_object:
# `response_object.json` contains the Python dict representation of the JSON-RPC response
print(json.dumps(response_object.json, indent=2))
else:
print("No response object (e.g., for a notification without 'id').")
# Simulate a request with authentication failure
print("\n--- Server processing authenticated request with wrong token ---")
auth_request_str = json.dumps({
"jsonrpc": "2.0",
"method": "secure_data",
"params": ["wrong_token"],
"id": "auth-req-456"
})
auth_response_object = JSONRPCResponseManager.handle(auth_request_str, dispatcher)
if auth_response_object:
print(json.dumps(auth_response_object.json, indent=2))
# --- Client-side logic (how to construct a JSON-RPC request) ---
# JSONRPCClient helps in constructing the request payload.
# It does NOT handle the actual network transport (e.g., HTTP POST).
# You would typically subclass it or use its .call() method to get the payload,
# then use a library like 'requests' to send it.
class MyDummyTransportClient(JSONRPCClient):
# This dummy client just prints the request payload
# In a real app, this method would send an HTTP POST request
# and return the response text.
def _send_request(self, request_str):
print(f"\n--- Client sending request payload ---\n{request_str}")
# In a real scenario, you'd send this via HTTP and get a response.
# For this quickstart, we'll return a simulated server response.
# Simulate the server handling this request
simulated_response_object = JSONRPCResponseManager.handle(request_str, dispatcher)
if simulated_response_object:
return json.dumps(simulated_response_object.json)
return json.dumps({
"jsonrpc": "2.0",
"error": {"code": -32000, "message": "Server error during simulation"},
"id": None
})
print("\n--- Client constructing and simulating a call ---")
client = MyDummyTransportClient(service_url="http://example.com/api") # URL is dummy for this example
result = client.call("greet", name="Alice")
print(f"Client received simulated result: {result}")
# Example of a client calling an RPC method that causes an error on the server
print("\n--- Client constructing and simulating an error-causing call ---")
error_result = client.call("secure_data", token="bad_token")
print(f"Client received simulated error result: {error_result}")
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'jsonrpc'
The Python interpreter cannot find the `jsonrpc` module. This often happens if the package `json-rpc` was not installed, or if an incorrect import name (e.g., `json_rpc`) was used.
fixEnsure the package is installed with `pip install json-rpc` and that your import statements use `import jsonrpc` or `from jsonrpc.<submodule> import ...`.
TypeError: JSONRPCResponseManager.handle() takes exactly 2 arguments (1 given)
The `handle` method of `JSONRPCResponseManager` expects two arguments: the raw JSON-RPC request string and a dispatcher (a dictionary or object mapping method names to functions).
fixCall `JSONRPCResponseManager.handle(request_string, dispatcher_object)` ensuring both arguments are provided and correctly typed.
json.decoder.JSONDecodeError: Expecting value: line X column Y (char Z)
The input string passed to `JSONRPCResponseManager.handle` is not valid JSON, or contains malformed data, preventing `json.loads()` from parsing it.
fixVerify that the incoming request payload is a well-formed JSON string. This error often indicates a client sending invalid data or a transport issue corrupting the payload.
Upgrade
Version history
1.15.0latest on PyPI · released Jun 11, 2023
Audit
Dependencies
sixrequiredPython 2/3 compatibility layer (often a transitive dependency, may not be strictly necessary for Python 3.7+)
werkzeugoptionalCommonly used for building HTTP/WSGI-based JSON-RPC servers, but not strictly required for the core protocol logic.