0
# Requests and Responses
1
2
Structured request and response objects for JSON-RPC 1.0 and 2.0 protocols with automatic serialization, validation, and comprehensive support for both single and batch operations.
3
4
## Capabilities
5
6
### JSON-RPC 2.0 Requests
7
8
Modern JSON-RPC 2.0 request objects with support for named and positional parameters, notifications, and batch processing.
9
10
```python { .api }
11
class JSONRPC20Request:
12
JSONRPC_VERSION = "2.0"
13
REQUIRED_FIELDS = {"jsonrpc", "method"}
14
POSSIBLE_FIELDS = {"jsonrpc", "method", "params", "id"}
15
16
def __init__(self, method: str = None, params = None, _id = None, is_notification: bool = None):
17
"""
18
Create JSON-RPC 2.0 request.
19
20
Parameters:
21
- method: Method name to invoke (required)
22
- params: Method parameters (list, dict, or None)
23
- _id: Request identifier (string, number, or None)
24
- is_notification: Whether this is a notification (no response expected)
25
"""
26
27
@classmethod
28
def from_json(cls, json_str: str):
29
"""Parse JSON string into request object."""
30
31
@classmethod
32
def from_data(cls, data):
33
"""Create request from parsed dict or list (for batch)."""
34
35
# Properties
36
method: str
37
params # list, dict, or None
38
_id # str, int, or None
39
is_notification: bool
40
data: dict
41
json: str
42
args: tuple # Positional parameters as tuple
43
kwargs: dict # Named parameters as dict
44
```
45
46
### JSON-RPC 1.0 Requests
47
48
Legacy JSON-RPC 1.0 request objects with array-only parameters and simplified structure.
49
50
```python { .api }
51
class JSONRPC10Request:
52
JSONRPC_VERSION = "1.0"
53
REQUIRED_FIELDS = {"method", "params", "id"}
54
POSSIBLE_FIELDS = {"method", "params", "id"}
55
56
def __init__(self, method: str = None, params = None, _id = None, is_notification: bool = None):
57
"""
58
Create JSON-RPC 1.0 request.
59
60
Parameters:
61
- method: Method name to invoke (required)
62
- params: Method parameters (list or tuple only)
63
- _id: Request identifier (any type except None for non-notifications)
64
- is_notification: Whether this is a notification
65
"""
66
67
@classmethod
68
def from_json(cls, json_str: str):
69
"""Parse JSON string into request object."""
70
71
@classmethod
72
def from_data(cls, data: dict):
73
"""Create request from parsed dict."""
74
75
# Properties
76
method: str
77
params: list
78
_id
79
is_notification: bool
80
data: dict
81
json: str
82
args: tuple
83
kwargs: dict
84
```
85
86
### Batch Requests
87
88
JSON-RPC 2.0 batch request container for processing multiple requests in a single call.
89
90
```python { .api }
91
class JSONRPC20BatchRequest:
92
JSONRPC_VERSION = "2.0"
93
94
def __init__(self, *requests):
95
"""
96
Create batch request container.
97
98
Parameters:
99
- requests: Variable number of JSONRPC20Request objects
100
"""
101
102
@classmethod
103
def from_json(cls, json_str: str):
104
"""Parse JSON array string into batch request."""
105
106
# Properties
107
requests: tuple
108
json: str
109
110
def __iter__(self):
111
"""Iterate over individual requests."""
112
```
113
114
### JSON-RPC 2.0 Responses
115
116
Response objects for JSON-RPC 2.0 with result or error data and proper correlation with requests.
117
118
```python { .api }
119
class JSONRPC20Response:
120
JSONRPC_VERSION = "2.0"
121
122
def __init__(self, **kwargs):
123
"""
124
Create JSON-RPC 2.0 response.
125
126
Parameters:
127
- result: Success result (mutually exclusive with error)
128
- error: Error object dict (mutually exclusive with result)
129
- _id: Request ID for correlation
130
"""
131
132
# Properties
133
result # Any type
134
error: dict # Error object
135
_id # str, int, or None
136
data: dict
137
json: str
138
request # Associated request object
139
```
140
141
### JSON-RPC 1.0 Responses
142
143
Response objects for JSON-RPC 1.0 with simplified structure.
144
145
```python { .api }
146
class JSONRPC10Response:
147
JSONRPC_VERSION = "1.0"
148
149
def __init__(self, **kwargs):
150
"""
151
Create JSON-RPC 1.0 response.
152
153
Parameters:
154
- result: Success result (mutually exclusive with error)
155
- error: Error object dict (mutually exclusive with result)
156
- _id: Request ID (required, cannot be None)
157
"""
158
159
# Properties
160
result # Any type
161
error: dict
162
_id # Required, not None
163
data: dict
164
json: str
165
request # Associated request object
166
```
167
168
### Batch Responses
169
170
Container for multiple JSON-RPC 2.0 responses from batch request processing.
171
172
```python { .api }
173
class JSONRPC20BatchResponse:
174
JSONRPC_VERSION = "2.0"
175
176
def __init__(self, *responses):
177
"""
178
Create batch response container.
179
180
Parameters:
181
- responses: Variable number of response objects
182
"""
183
184
# Properties
185
responses: tuple
186
data: list
187
json: str
188
request # Associated batch request
189
190
def __iter__(self):
191
"""Iterate over individual responses."""
192
```
193
194
## Usage Examples
195
196
### Creating and Parsing Requests
197
198
```python
199
from jsonrpc.jsonrpc2 import JSONRPC20Request
200
from jsonrpc.jsonrpc1 import JSONRPC10Request
201
202
# JSON-RPC 2.0 with named parameters
203
request = JSONRPC20Request(
204
method="subtract",
205
params={"minuend": 42, "subtrahend": 23},
206
_id=1
207
)
208
print(request.json)
209
# {"jsonrpc": "2.0", "method": "subtract", "params": {"minuend": 42, "subtrahend": 23}, "id": 1}
210
211
# JSON-RPC 2.0 with positional parameters
212
request = JSONRPC20Request(
213
method="subtract",
214
params=[42, 23],
215
_id=2
216
)
217
print(request.json)
218
# {"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 2}
219
220
# JSON-RPC 2.0 notification (no response expected)
221
notification = JSONRPC20Request(
222
method="update",
223
params=[1, 2, 3, 4, 5],
224
is_notification=True
225
)
226
print(notification.json)
227
# {"jsonrpc": "2.0", "method": "update", "params": [1, 2, 3, 4, 5]}
228
229
# JSON-RPC 1.0 request
230
request_v1 = JSONRPC10Request(
231
method="subtract",
232
params=[42, 23],
233
_id=1
234
)
235
print(request_v1.json)
236
# {"method": "subtract", "params": [42, 23], "id": 1}
237
```
238
239
### Parsing JSON Strings
240
241
```python
242
from jsonrpc.jsonrpc import JSONRPCRequest
243
244
# Auto-detect version and parse
245
json_str = '{"jsonrpc": "2.0", "method": "add", "params": [1, 2], "id": 1}'
246
request = JSONRPCRequest.from_json(json_str)
247
print(type(request).__name__) # JSONRPC20Request
248
print(request.method) # add
249
print(request.args) # (1, 2)
250
251
# JSON-RPC 1.0 (no "jsonrpc" field)
252
json_str = '{"method": "add", "params": [1, 2], "id": 1}'
253
request = JSONRPCRequest.from_json(json_str)
254
print(type(request).__name__) # JSONRPC10Request
255
256
# Batch request
257
batch_json = '''[
258
{"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"},
259
{"jsonrpc": "2.0", "method": "notify_hello", "params": [7]},
260
{"jsonrpc": "2.0", "method": "subtract", "params": [42,23], "id": "2"}
261
]'''
262
batch_request = JSONRPCRequest.from_json(batch_json)
263
print(type(batch_request).__name__) # JSONRPC20BatchRequest
264
print(len(batch_request.requests)) # 3
265
```
266
267
### Working with Parameters
268
269
```python
270
# Access parameters in different ways
271
request = JSONRPC20Request(
272
method="calculate",
273
params={"operation": "add", "x": 10, "y": 5}
274
)
275
276
# As keyword arguments
277
print(request.kwargs) # {"operation": "add", "x": 10, "y": 5}
278
print(request.args) # ()
279
280
# Positional parameters
281
request2 = JSONRPC20Request(method="add", params=[10, 5])
282
print(request2.args) # (10, 5)
283
print(request2.kwargs) # {}
284
285
# Mixed access for method dispatch
286
def my_method(*args, **kwargs):
287
return sum(args) + sum(kwargs.values())
288
289
result = my_method(*request2.args, **request2.kwargs) # 15
290
```
291
292
### Creating Responses
293
294
```python
295
from jsonrpc.jsonrpc2 import JSONRPC20Response
296
from jsonrpc.exceptions import JSONRPCError
297
298
# Success response
299
response = JSONRPC20Response(result=42, _id=1)
300
print(response.json)
301
# {"jsonrpc": "2.0", "result": 42, "id": 1}
302
303
# Error response
304
error = JSONRPCError(code=-32602, message="Invalid params", data={"param": "x"})
305
response = JSONRPC20Response(error=error._data, _id=1)
306
print(response.json)
307
# {"jsonrpc": "2.0", "error": {"code": -32602, "message": "Invalid params", "data": {"param": "x"}}, "id": 1}
308
309
# Link response to request
310
response.request = request
311
```
312
313
### Batch Processing
314
315
```python
316
from jsonrpc.jsonrpc2 import JSONRPC20BatchRequest, JSONRPC20BatchResponse
317
318
# Create individual requests
319
req1 = JSONRPC20Request(method="add", params=[1, 2], _id=1)
320
req2 = JSONRPC20Request(method="multiply", params=[3, 4], _id=2)
321
req3 = JSONRPC20Request(method="notify", params=["hello"], is_notification=True)
322
323
# Create batch
324
batch = JSONRPC20BatchRequest(req1, req2, req3)
325
print(batch.json)
326
327
# Process responses
328
resp1 = JSONRPC20Response(result=3, _id=1)
329
resp2 = JSONRPC20Response(result=12, _id=2)
330
# No response for notification
331
332
batch_response = JSONRPC20BatchResponse(resp1, resp2)
333
print(batch_response.json)
334
# [{"jsonrpc": "2.0", "result": 3, "id": 1}, {"jsonrpc": "2.0", "result": 12, "id": 2}]
335
```