Tastypie is a reusable app (that is, it relies only on its own code and focuses on providing just a REST-style API) and is suitable for providing an API to any application without having to modify the sources of that app.
Not everyone’s needs are the same, so Tastypie goes out of its way to provide plenty of hooks for overriding or extending how it works.
For example purposes, we’ll be adding an API to a simple blog application.
The only mandatory configuration is adding 'tastypie' to your INSTALLED_APPS. This isn’t strictly necessary, as Tastypie has only two non-required models, but may ease usage.
Here is myapp/models.py:
from tastypie.utils.timezone import now
from django.contrib.auth.models import User
from django.db import models
from django.utils.text import slugify
class Entry(models.Model):
user = models.ForeignKey(User)
pub_date = models.DateTimeField(default=now)
title = models.CharField(max_length=200)
slug = models.SlugField(null=True, blank=True)
body = models.TextField()
Creating Resources
REST-style architecture talks about resources, so unsurprisingly integrating with Tastypie involves creating Resource classes. For our simple application, we’ll create a file for these in myapp/api.py, though they can live anywhere in your application:
from tastypie.resources import ModelResource
from myapp.models import Entry
class EntryResource(ModelResource):
class Meta:
queryset = Entry.objects.all()
resource_name = 'entry'
In REST everything is a resource, means objects are described as resources. So for creating a Tastypie REST API involves in creating a resource class. To create a resource, we need to subclass ModelResource class. This EntryResource class will check all the non-relational fields on the Entry model and create its own Api fields. This works just like the ModelForm of Django Forms.
Hooking Up The Resource: Afrer creating the Resource, we need to tell the Django, that a resource is created by hooking our EntryResource to the URL.
from django.conf.urls import url, include
from myapp.api import EntryResource
entry_resource = EntryResource()
urlpatterns = [
url(r'^blog/', include('myapp.urls')),
url(r'^api/', include(entry_resource.urls)),
]
Now if we check on localhost:8000/api/entry/ we will get the API response.
(The resource_name within the Meta class is optional. If not provided, it is automatically generated off the classname, removing any instances of Resource and lowercasing the string. So EntryResource would become just entry. That's why in the URL we specified ../entry/ )