Wednesday, June 5, 2013

We have an API!

So after the initial few scares, DRF ride proved to be smooth and we have a reasonable looking Publication level API. It is interesting how building an API makes you think about certain representations you chose in your model.

For example, motivated by the presence of Metadata EPub3 that can be several level deep, I decided to keep all the metadata as a single dict stored as JSON in the db. This allows me to capture metadata any level deep. What do I mean by deep metadata? An EPub file can not only have metadata like Title, it can have metadata explaining some property of the title. For example, title may have a language and then language may have a family.

However this means that all this data is not easily available for direct access and manipulation. So I had setup the access to the title of the Publication through a property.


@property
def title(self):
    return self.mtdt['title']['text']

This was nice and dandy since DRF allows you to use any function on the model as a source for a field till it takes only self as an argument. But as soon as I tried to create a new pub through API, I ran into a problem. I knew how to setup readonly properties but not how to update them. It turns out, it is quite easy:
# define a setter for the property
@title.setter
def title(self, val):
    if 'title' in self.mtdt:
        self.mtdt['title']['text'] = val
    else:
        self.mtdt['title'] = {'text': val}

There is a similar deleter decorator as well.

So with this, title is now a read and write property on the model and can be used seamlessly through the API. However I realized that it makes sense to give the Publication its own title that is separate from the title of the book. Kind of like project title. And that it what I did. I am also thinking of opening up the metadata dict and store the individual items as generic metadata attached to the publication. But that is for some other time.

Now that we have a rudimentary API for the Publications going, it is time to head back to the ugly world of Javascript and see if Backbone fulfills its promise.

No comments:

Post a Comment