Sunday, October 12, 2008

A resource style implementation

If you are thinking of implementing a RESTful web service, it should follow a resource oriented architecture. Naturally, a key abstraction in this implementation would be a resource. Here is a sample resource diagram:

Now this is a pretty trivial class and one that is not terribly useful on its own. The idea that it represents within the context of a resource oriented architecture is a powerful one. If we can design a resource abstraction before concerning ourselves HTTP and other deployment concerns, we have have a better chance of getting the design right.

The above class implemented in Python might look like this.
class Resource:
def __init__(self):

def set_uuid(self, uuid):

def set_name(self, name):

def set_content(self, content):

def set_timestamp(self, timestamp):

def get_uuid(self):
return self.uuid

def get_name(self):

def get_content(self):
return self.content

def get_timestamp(self):
return self.timestamp
Again, fairly straightforward and not terribly useful on its own. It is a useful start to implementing a resource oriented architecture. This class could be extended in several ways to be more useful in an application. For instance, the content attribute could actually be a resource representation. This is another abstraction in our architecture.
This simple class will take any object and turn it into a representation we can use. Python helps us out here by allowing us to override the __repr__() method to get a string representation of the object when we return it.

As it stands we have two classes; Resource and Representation. The Resource class is anything in our resource oriented system. We then suggested a potential Representation class that will turn any object into a representation to be defined by __repr__(). I'm not going to go into much detail of how the __repr__() implementation might look like because the possibilities are so limitless. I'll save that for another discussion.

Here is how we could potentially use the two classes we have defined above.
if __name__=='__main__':
rep_obj.set_obj({'date': 'now', 'title': 'My Title'})

First, we create a representation of some object, in this case a dictionary. We then create a resource for this representation. Usually, the resource will determine the resource type upon request from a client. For demonstration purposes, I've elided these details.

The important idea to take away from this discussion is that when implementing a resource oriented architecture, the concept of resource and resource representation can be built independently of the problem domain.