<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=338168267432629&amp;ev=PageView&amp;noscript=1">
Programming

Django TastyPie

Django Tastypie makes developing RESTful APIs for web applications so delicious that you’ll crave for more! In developing web applications, there may come a point where you’ll have to expose your platform to third-party developers or to your very own mobile application. And that’s when Django Tastypie will come in …


Django Tastypie makes developing RESTful APIs for web applications so delicious that you’ll crave for more! In developing web applications, there may come a point where you’ll have to expose your platform to third-party developers or to your very own mobile application. And that’s when Django Tastypie will come in handy—or tasty.

We’ll be using the Polls web application in the Django tutorials. At the end of this tutorial, we’ll be able to create, read, update and delete polls through the API.

Setup Project

  1. Install using pip: pip install django-tastypie
  2. Add ‘tastypie’ to installed apps in your sample_project/settings.py
  3. Then sync your db: ./manage.py syncdb
  4. Optional. Set TASTYPIE_FULL_DEBUG to True in your sample_project/local_settings.py

Create PollResource

We can now create our API. First off, create polls/api.py and the PollResource.

 # polls/api.py 
from tastypie.resources import ModelResource 
from polls.models import Poll 

class PollResource(ModelResource): 
    class Meta: queryset = Poll.objects.all() 

Now we should add our PollResource to the sample_project/urls.py.

# sample_project/urls.py
from django.conf.urls import patterns, include, url 
from polls.api import PollResource 

poll_resource = PollResource() 
urlpatterns = patterns('', 
    url(r'^polls/', include('polls.urls', namespace='polls')), 
    url(r'^api/', include(poll_resource.urls)), 
) 

Let’s test our newly created API! Go to http://127.0.0.1:8000/api/poll/?format=json.

Pretty Print JSON

You’re probably wondering how you would debug a one-liner JSON output from your API. No worries, we’ll get it pretty-printed in no time. Edit your polls/api.py to look like the code below.

# polls/api.py 
from django.core.serializers import json 
from django.utils import simplejson 
from tastypie.serializers import Serializer 
from tastypie.resources import ModelResource 
from polls.models import Poll 

class PrettyJSONSerializer(Serializer): 
    json_indent = 4 

    def to_json(self, data, options=None): 
        options = options or {} 
        data = self.to_simple(data, options) 
        return simplejson.dumps(data, cls=json.DjangoJSONEncoder, sort_keys=True, ensure_ascii=False, indent=self.json_indent) 

class PollResource(ModelResource): 
    class Meta: queryset = Poll.objects.all() 
    serializer = PrettyJSONSerializer()

Create ChoiceResource

Let’s add ChoiceResource to the API. Edit your polls/api.py to add the code below.

# polls/api.py 
# ... 
from tastypie import fields 
from polls.models import Poll, Choice 
# ... 

class PollResource(ModelResource): 
    choices = fields.ToManyField('polls.api.ChoiceResource', 'choice_set', related_name='poll', full=True) 
    class Meta: 
        queryset = Poll.objects.all() 
        serializer = PrettyJSONSerializer() 


class ChoiceResource(ModelResource): 
    poll = fields.ForeignKey('polls.api.PollResource', 'poll', related_name='choices') 

    class Meta: 
        queryset = Choice.objects.all() 
        serializer = PrettyJSONSerializer() 

Note that we used full=True for the choices field in PollResource. This makes it easy for us to debug our API. But in production, you should set full to False unless you know what you’re doing.

CRUD API

We now have an API that can read all the polls and choices. We will now implement the create, update and delete functionality of our API. We simply edit these few lines in polls/api.py.

# polls/api.py 
# ... 
from tastypie.authorization from Authorization 

class PollResource(ModelResource): 
    choices = fields.ToManyField('polls.api.ChoiceResource', 'choice_set', related_name='poll', full=True) 
    
    class Meta: 
        queryset = Poll.objects.all() 
        serializer = PrettyJSONSerializer() 
        authorization = Authorization() 

class ChoiceResource(ModelResource): 
    poll = fields.ForeignKey('polls.api.PollResource', 'poll', related_name='choices') 
    
    class Meta: 
        queryset = Choice.objects.all() 
        serializer = PrettyJSONSerializer() 
        authorization = Authorization() 

Testing with REST Console

To test the CRUD functionality of our API, we can use curl, but I prefer to use REST Console, a chrome-extension.

GET Request

First, we’re going to send a GET Request on http://127.0.0.1:8000/api/v1/poll/.

  1. Set Target Request URI to http://127.0.0.1:8000/api/v1/poll/
  2. Set Target Request Method to GET
  3. Set Accept Content-Type to application/json
  4. Click on the send button

PATCH Request

If you want to update just a subset of the field, you would use PATCH, otherwise use PUT. But for this tutorial, we’ll just be using PATCH.

  1. Set Target Request URI to http://127.0.0.1:8000/api/v1/poll/1/Change the URI appropriately.
  2. Set Target Request Method to PATCH
  3. Set Content Headers Content-Type to application/json
  4. Set Request Payload Raw Body to {"question": "What's your favorite color?"}.
  5. Click on the send button
  6. Check the Response Headers if the status code is 202

POST Request

To create an object, we simply send a POST request to http://127.0.0.1:8000/api/v1/poll/. We’ll be using the same settings as the PATCH request.

  1. Set Target Request URI to http://127.0.0.1:8000/api/v1/poll/
  2. Set Target Request Method to POST
  3. Set Request Payload Raw Body to {"choices": [{"choice_text": "Male"}, {"choice_text": "Female"}], "question": "What\'s your gender?"}.
  4. Click on the send button
  5. Check the Response Headers if the status code is 201

Remarks

I’ll leave it to the reader as an exercise on how to do the DELETE request. I hope you had fun tasting this delicious Django App.

Similar posts

Get notified about the latest in Tech

Be the first to know about new tech from the experts at Bixly!