Sunday, June 2, 2013

Building a REST API using Django Rest Framework

It was a God forsaken day when I decided to build the front end of Instascribe using Backbone. I was so happy with my existing Spaghetti DOM code. It made me feel like a gladiator in the Roman Colosseum. But then good times never last.

As soon as I started using Backbone, it wanted REST. So much for a robust framework. It is thus that I found myself in need of a RESTful API for my Django app. My previous attempt at an API had produced a jungle of api endpoints that was as diverse as Amazon. The return values of the endpoints were also all over the map, sometimes returning html, sometimes json. (It is but natural that one would use the format that is easiest for the job at hand.)

But they say, to get REST, you need to be consistent. As I started cleaning up my code, I realized that there are other important things related to APIs that I have not yet thought about. Things like permissions, rate control, discovery. So I looked around and found django-tastypie and django-rest-framework. While Django tastypie sounded delicious and I was already feeling ravenous having lost my spaghetti, it lost the battle to django-rest-framework on account of its hydrate and dehydrate functions. No way I am going to write functions that are called hydrate and dehydrate in my web application code. I found the class based approach of writing serializers in django-rest-framework a lot more intuitive and cleaner.

The examples in the documentation of drf are varied and well written giving the impression that it will work fine for my use case (which, for some strange reason, almost always turns out to be that corner case that is still pending implementation).

So now I am busy building my new API using django-rest-framework. It is time to REST!

No comments:

Post a Comment