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.
52 >>> server = jsonrpclib.Server('http://localhost:8080')
55 >>> print jsonrpclib.history.request
56 {"jsonrpc": "2.0", "params": [5, 6], "id": "gb3c9g37", "method": "add"}
57 >>> print jsonrpclib.history.response
58 {'jsonrpc': '2.0', 'result': 11, 'id': 'gb3c9g37'}
59 >>> server.add(x=5, y=10)
61 >>> server._notify.add(5,6)
62 # No result returned...
63 >>> batch = jsonrpclib.MultiCall(server)
65 >>> batch.ping({'key':'value'})
66 >>> batch._notify.add(4, 30)
68 >>> for result in results:
72 # Note that there are only two responses -- this is according to spec.
75 If you need 1.0 functionality, there are a bunch of places you can pass that
76 in, although the best is just to change the value on
77 jsonrpclib.config.version:
81 >>> jsonrpclib.config.version
83 >>> jsonrpclib.config.version = 1.0
84 >>> server = jsonrpclib.Server('http://localhost:8080')
87 >>> print jsonrpclib..history.request
88 {"params": [7, 10], "id": "thes7tl2", "method": "add"}
89 >>> print jsonrpclib.history.response
90 {'id': 'thes7tl2', 'result': 17, 'error': None}
94 The equivalent loads and dumps functions also exist, although with minor
95 modifications. The dumps arguments are almost identical, but it adds three
96 arguments: rpcid for the 'id' key, version to specify the JSON-RPC
97 compatibility, and notify if it's a request that you want to be a
100 Additionally, the loads method does not return the params and method like
101 xmlrpclib, but instead a.) parses for errors, raising ProtocolErrors, and
102 b.) returns the entire structure of the request / response for manual parsing.
106 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.
109 from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
111 server = SimpleJSONRPCServer(('localhost', 8080))
112 server.register_function(pow)
113 server.register_function(lambda x,y: x+y, 'add')
114 server.register_function(lambda x: x, 'ping')
115 server.serve_forever()
120 I've recently added "automatic" class translation support, although it is
121 turned off by default. This can be devastatingly slow if improperly used, so
122 the following is just a short list of things to keep in mind when using it.
124 * Keep It (the object) Simple Stupid. (for exceptions, keep reading.)
125 * Do not require init params (for exceptions, keep reading)
126 * Getter properties without setters could be dangerous (read: not tested)
128 If any of the above are issues, use the _serialize method. (see usage below)
129 The server and client must BOTH have use_jsonclass configuration item on and
130 they must both have access to the same libraries used by the objects for
133 If you have excessively nested arguments, it would be better to turn off the
134 translation and manually invoke it on specific objects using
135 jsonrpclib.jsonclass.dump / jsonrpclib.jsonclass.load (since the default
136 behavior recursively goes through attributes and lists / dicts / tuples).
141 # This object is /very/ simple, and the system will look through the
142 # attributes and serialize what it can.
143 class TestObj(object):
146 # This object requires __init__ params, so it uses the _serialize method
147 # and returns a tuple of init params and attribute values (the init params
148 # can be a dict or a list, but the attribute values must be a dict.)
149 class TestSerial(object):
151 def __init__(self, *args):
153 def _serialize(self):
154 return (self.args, {'foo':self.foo,})
163 jsonrpclib.config.use_jsonclass = True
165 testobj1 = test_obj.TestObj()
166 testobj2 = test_obj.TestSerial()
167 server = jsonrpclib.Server('http://localhost:8080')
168 # The 'ping' just returns whatever is sent
169 ping1 = server.ping(testobj1)
170 ping2 = server.ping(testobj2)
171 print jsonrpclib.history.request
172 # {"jsonrpc": "2.0", "params": [{"__jsonclass__": ["test_obj.TestSerial", ["foo"]]}], "id": "a0l976iv", "method": "ping"}
173 print jsonrpclib.history.result
174 # {'jsonrpc': '2.0', 'result': <test_obj.TestSerial object at 0x2744590>, 'id': 'a0l976iv'}
177 To turn on this behaviour, just set jsonrpclib.config.use_jsonclass to True.
178 If you want to use a different method for serialization, just set
179 jsonrpclib.config.serialize_method to the method name. Finally, if you are
180 using classes that you have defined in the implementation (as in, not a
181 separate library), you'll need to add those (on BOTH the server and the
182 client) using the jsonrpclib.config.classes.add() method.
183 (Examples forthcoming.)
185 Feedback on this "feature" is very, VERY much appreciated.
189 In my opinion, there are several reasons to choose JSON over XML for RPC:
191 * Much simpler to read (I suppose this is opinion, but I know I'm right. :)
192 * Size / Bandwidth - Main reason, a JSON object representation is just much smaller.
193 * Parsing - JSON should be much quicker to parse than XML.
194 * Easy class passing with jsonclass (when enabled)
196 In the interest of being fair, there are also a few reasons to choose XML
199 * Your server doesn't do JSON (rather obvious)
200 * Wider XML-RPC support across APIs (can we change this? :))
201 * Libraries are more established, i.e. more stable (Let's change this too.)
205 I've dropped almost-verbatim tests from the JSON-RPC spec 2.0 page.
212 * Use HTTP error codes on SimpleJSONRPCServer
213 * Test, test, test and optimize