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.
pip install django-tastypie
sample_project/settings.py
./manage.py syncdb
TASTYPIE_FULL_DEBUG
to True
in your sample_project/local_settings.py
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
.
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()
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.
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()
To test the CRUD functionality of our API, we can use curl, but I prefer to use REST Console, a chrome-extension.
First, we’re going to send a GET
Request on http://127.0.0.1:8000/api/v1/poll/
.
http://127.0.0.1:8000/api/v1/poll/
GET
application/json
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
.
http://127.0.0.1:8000/api/v1/poll/1/
. Change the URI appropriately.PATCH
application/json
{"question": "What's your favorite color?"}
.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.
http://127.0.0.1:8000/api/v1/poll/
POST
{"choices": [{"choice_text": "Male"}, {"choice_text": "Female"}], "question": "What\'s your gender?"}
.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.