DjangoCon 2011 – Building APIs in Django with Tastypie

Building APIs in Django with Tastypie by Issac Kelly

Tastypie is one of a couple of frameworks for building APIs with Django. Issac will go over some of the reasons you might pick Tastypie, and how to implement a Tastypie on top of an existing Django project.

Updates Below:

17.48

Question time. Great talk.

17.41

Just going over examples. You can view the code at https://github.com/issackelly/Building-Web-APIs-for-Django-with-Tastypie-Talk

17.34

What else comes with Tastypie:

  • Serialization Methods (JSON, Binary plist, YAML, XML, pretty much anything you want)
  • Authentication Classes (NO-OP, API Key, Http Basic Auth and Digest, again anything you want)
  • Authorization Classes (Read Only, Default Authorized, Django Authorization)
  • Everything is Class based so you can extend it all

17.30

Tastypie separates authentication and authorization.

17.29

Way to create API with Tastypie

#models.py
class Project(TitleSlugDescriptionModel):
    """
    Stores the projects that corkboards belong to.
    Only administrators should be able to set these up
    """
 
    user = models.ForeignKey(User)
    members = models.ManyToManyField(User, related_name="ProjectMember")
    created_on = models.DateTimeField(_('Created On'), default=datetime.now, editable=False)
    updated_on = models.DateTimeField(_('Updated On'), editable=False, null=True, blank=True)
 
    class Meta:
        ordering = ['-created_on',]
 
    def __unicode__(self):
        return '%s' % (self.title)
 
    def save(self, *args, **kwargs):
        self.updated_on = datetime.now()
        super(Project, self).save()
 
#Easy Way
class ProjectResource(ModelResource):
 
    class Meta:
        queryset = Project.objects.all
 
#More Thorough Way
class ProjectResource(ModelResource):
 
    corkboards = fields.ToManyField("loupe.api.CorkboardResource", "corkboard_set", full=True)
 
    def get_object_list(self, request, *args, **kwargs):
        return Project.objects.filter(members=request.user)
 
    class Meta:
        queryset = Project.objects.all()
        authentication = BasicAuthentication()
        authorization = DjangoAuthorization()
        allowed_methods = ["get", "post"]
        ordering = ['created_on', 'updated_on']
        filtering = {
            'members': ALL_WITH_RELATIONS,
            'title': ALL,
            'description': ALL,
        }

17.24

Why Tastypie?

  • Well Tested
  • HATEOAS
  • Good features and support, fits well into existing ORM thinking
  • Totally extensible
  • Works well with JavaScript
  • Cool stuff is coming out of the community

17.22

Can follow along at http://bit.ly/nwfYvI