Skip to content
This repository has been archived by the owner on Sep 17, 2023. It is now read-only.

18 API with Tastypie

scotwk edited this page May 10, 2015 · 5 revisions

Django lets you return JSON from a view, but designing an API is a lot of work. Fortunately someone has already done that for you. We will use the Tastypie package.

Installing Tastypie

The version of Tastypie that pip will find by default is not new enough for Django 1.8, so install the latest version from Github:

$ pip install -e git+https://github.com/django-tastypie/django-tastypie#egg=TastyPie

Tastypie offers an easy way to build an API: https://django-tastypie.readthedocs.org/en/latest/

Setup

In elevennote/settings.py modify INSTALLED_APPS and add

INSTALLED_APPS = [
    ...
    `tastypie`,
]

In elevennote/urls.py add in the following lines:

from tastypie.api import Api
from note.api.resources import NoteResource

v1_api = Api(api_name='v1')
v1_api.register(NoteResource())

...

url(r'^api/', include(v1_api.urls)),

Define resources

Make a note/api/resources.py and create a NoteResource to define how the API will serve the note model.

from tastypie.resources import ModelResource
from ..models import Note


class NoteResource(ModelResource):
    class Meta:
        queryset = Note.objects.all()
        allowed_methods = ['get']

Using the API

Schema: http://localhost:8000/api/v1/note/schema/?format=json

List: http://localhost:8000/api/v1/note/?format=json

Note: in order to make the API more interesting we have loosened the restriction here that prevents seeing other users posts. (For that matter, our API is wide open. Anyone can access the data, even people who are not authenticated. We will get to that later.)