The Python Message Class: How I Implement REST based JSON Webservices

Coming from a background in .NET development and building SOAP web services in ASP.NET, I found it strange and in some ways like a step backwards to implement and consume web services in a REST style using JSON to structure the message.

In a sense some of this was natural in Python. JSON is nothing more than a serialized Python dictionary. However, the contract between the service and any consuming client that I was writing felt very loose. One typo in a key in the construction of a dictionary of data to pass as a message from the client to the service or visa versa would result in nasty little exceptions that were sometimes hard to Debug.

Then the other day, I noticed Ned's post on "Upgrading from lists to objects" and it hit me as all too often extremely obvious things that go unrealized until they slap you in the face do. What I need to do is centralize that contract in a class that both the service and the client can share.

So, I created a base class to base all of my message structures on called JsonMessage. This class provided some base functionality (like validating that the string with which to deserialize was valid JSON). The idea is simple. The class has different members representing the data of the message. There are two methods on the class, serialize() and deserialize(json).

The first, serialize(), takes all the data of the class and structures it into a dictionary, which is fed to simplejson.dumps() so the resulting string can be sent over the wire. On the other side of this communication, the request.read() contents is passed to deserialize(json) and in this method, simplejson.loads(json) constructs a dictionary and from this dictionary all the members of the class are populated. Now you have a hydrated object with which to act upon and neither the service code nor the client code has to fool with dictionary key strings or value manipulation. Furthermore, all the details of how this object serializes/deserialized for transfer over HTTP occurs in a single place.

Tags: python, rest, json, programming, software