3 This library is an implementation of the JSON-RPC specification.
4 It supports both the original 1.0 specification, as well as the
5 new (proposed) 2.0 spec, which includes batch submission, keyword
8 It is licensed under the Apache License, Version 2.0
9 (http://www.apache.org/licenses/LICENSE-2.0.html).
13 Feel free to send any questions, comments, or patches to our Google Group
14 mailing list (you'll need to join to send a message):
15 http://groups.google.com/group/jsonrpclib
19 This library implements the JSON-RPC 2.0 proposed specification in pure Python.
20 It is designed to be as compatible with the syntax of xmlrpclib as possible
21 (it extends where possible), so that projects using xmlrpclib could easily be
22 modified to use JSON and experiment with the differences.
24 It is backwards-compatible with the 1.0 specification, and supports all of the
25 new proposed features of 2.0, including:
27 * Batch submission (via MultiCall)
29 * Notifications (both in a batch and 'normal')
30 * Class translation using the 'jsonclass' key.
32 I've added a "SimpleJSONRPCServer", which is intended to emulate the
33 "SimpleXMLRPCServer" from the default Python distribution.
37 It supports cjson and simplejson, and looks for the parsers in that order
38 (searching first for cjson, then for the "built-in" simplejson as json in 2.6+,
39 and then the simplejson external library). One of these must be installed to
40 use this library, although if you have a standard distribution of 2.6+, you
41 should already have one. Keep in mind that cjson is supposed to be the
42 quickest, I believe, so if you are going for full-on optimization you may
48 This is (obviously) taken from a console session.
51 >>> server = jsonrpclib.Server('http://localhost:8080')
54 >>> print jsonrpclib.history.request
55 {"jsonrpc": "2.0", "params": [5, 6], "id": "gb3c9g37", "method": "add"}
56 >>> print jsonrpclib.history.response
57 {'jsonrpc': '2.0', 'result': 11, 'id': 'gb3c9g37'}
58 >>> server.add(x=5, y=10)
60 >>> server._notify.add(5,6)
61 # No result returned...
62 >>> batch = jsonrpclib.MultiCall(server)
64 >>> batch.ping({'key':'value'})
65 >>> batch._notify.add(4, 30)
67 >>> for result in results:
71 # Note that there are only two responses -- this is according to spec.
73 If you need 1.0 functionality, there are a bunch of places you can pass that
74 in, although the best is just to change the value on
75 jsonrpclib.config.version:
78 >>> jsonrpclib.config.version
80 >>> jsonrpclib.config.version = 1.0
81 >>> server = jsonrpclib.Server('http://localhost:8080')
84 >>> print jsonrpclib..history.request
85 {"params": [7, 10], "id": "thes7tl2", "method": "add"}
86 >>> print jsonrpclib.history.response
87 {'id': 'thes7tl2', 'result': 17, 'error': None}
90 The equivalent loads and dumps functions also exist, although with minor
91 modifications. The dumps arguments are almost identical, but it adds three
92 arguments: rpcid for the 'id' key, version to specify the JSON-RPC
93 compatibility, and notify if it's a request that you want to be a
96 Additionally, the loads method does not return the params and method like
97 xmlrpclib, but instead a.) parses for errors, raising ProtocolErrors, and
98 b.) returns the entire structure of the request / response for manual parsing.
102 This is identical in usage (or should be) to the SimpleXMLRPCServer in the default Python install. Some of the differences in features are that it obviously supports notification, batch calls, class translation (if left on), etc. Note: The import line is slightly different from the regular SimpleXMLRPCServer, since the SimpleJSONRPCServer is distributed within the jsonrpclib library.
104 from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
106 server = SimpleJSONRPCServer(('localhost', 8080))
107 server.register_function(pow)
108 server.register_function(lambda x,y: x+y, 'add')
109 server.register_function(lambda x: x, 'ping')
110 server.serve_forever()
114 I've recently added "automatic" class translation support, although it is
115 turned off by default. This can be devastatingly slow if improperly used, so
116 the following is just a short list of things to keep in mind when using it.
118 * Keep It (the object) Simple Stupid. (for exceptions, keep reading.)
119 * Do not require init params (for exceptions, keep reading)
120 * Getter properties without setters could be dangerous (read: not tested)
122 If any of the above are issues, use the _serialize method. (see usage below)
123 The server and client must BOTH have use_jsonclass configuration item on and
124 they must both have access to the same libraries used by the objects for
127 If you have excessively nested arguments, it would be better to turn off the
128 translation and manually invoke it on specific objects using
129 jsonrpclib.jsonclass.dump / jsonrpclib.jsonclass.load (since the default
130 behavior recursively goes through attributes and lists / dicts / tuples).
134 # This object is /very/ simple, and the system will look through the
135 # attributes and serialize what it can.
136 class TestObj(object):
139 # This object requires __init__ params, so it uses the _serialize method
140 # and returns a tuple of init params and attribute values (the init params
141 # can be a dict or a list, but the attribute values must be a dict.)
142 class TestSerial(object):
144 def __init__(self, *args):
146 def _serialize(self):
147 return (self.args, {'foo':self.foo,})
154 jsonrpclib.config.use_jsonclass = True
156 testobj1 = test_obj.TestObj()
157 testobj2 = test_obj.TestSerial()
158 server = jsonrpclib.Server('http://localhost:8080')
159 # The 'ping' just returns whatever is sent
160 ping1 = server.ping(testobj1)
161 ping2 = server.ping(testobj2)
162 print jsonrpclib.history.request
163 # {"jsonrpc": "2.0", "params": [{"__jsonclass__": ["test_obj.TestSerial", ["foo"]]}], "id": "a0l976iv", "method": "ping"}
164 print jsonrpclib.history.result
165 # {'jsonrpc': '2.0', 'result': <test_obj.TestSerial object at 0x2744590>, 'id': 'a0l976iv'}
167 To turn on this behaviour, just set jsonrpclib.config.use_jsonclass to True.
168 If you want to use a different method for serialization, just set
169 jsonrpclib.config.serialize_method to the method name. Finally, if you are
170 using classes that you have defined in the implementation (as in, not a
171 separate library), you'll need to add those (on BOTH the server and the
172 client) using the jsonrpclib.config.classes.add() method.
173 (Examples forthcoming.)
175 Feedback on this "feature" is very, VERY much appreciated.
179 In my opinion, there are several reasons to choose JSON over XML for RPC:
181 * Much simpler to read (I suppose this is opinion, but I know I'm right. :)
182 * Size / Bandwidth - Main reason, a JSON object representation is just much smaller.
183 * Parsing - JSON should be much quicker to parse than XML.
184 * Easy class passing with jsonclass (when enabled)
186 In the interest of being fair, there are also a few reasons to choose XML
189 * Your server doesn't do JSON (rather obvious)
190 * Wider XML-RPC support across APIs (can we change this? :))
191 * Libraries are more established, i.e. more stable (Let's change this too.)
195 I've dropped almost-verbatim tests from the JSON-RPC spec 2.0 page.
202 * Use HTTP error codes on SimpleJSONRPCServer
203 * Test, test, test and optimize