April 22, 2012

We started using Tastypie recently to standardized our APIs and make them RESTful.

If you're using Tastypie, you've probably noticed that there's no built-in support for hierarchical resources. You'll also see "hierarchical resources" being referred to as "nested resources". For clarity, we'll use hierarchical resources for the rest of this post.

Hierarchical resources are useful. Many APIs (like Facebook and Twitter) use resource hierarchies. Consider the URI: "/users/1/posts/"
If you're using Tastypie w/o hierarchical resources, the same URI would look like: "/posts/?user=1", which doesn't look nearly as pretty or readable. It also doesn't make sense to access some resources without referring to another resource. For example, comments would go under posts and posts would go under users. Most of your access patterns would be getting posts for a user or retrieving comments for a post.
In addition to asethetics and readability, hierarchical resource URIs are easier to do URL based authorization on.

Adam has a blog post about adding hierarchical resource support in Tastypie, but I was unable to get it fully working. It doesn't support all operations that Tastypie supports, namely get_list(). The Tastypie cookbook also provides code for supporting resource hierarchy but it's not generic enough.

So, we decided to roll our own, borrowing ideas from both Adam's blog post and the Tastypie cookbook. See this gist for the code.

blog comments powered by Disqus