Django tasty pie logo

Create a Super Basic REST API with Django Tastypie

by Real Python api django projects web-dev

Let’s set up a RESTful API with Django Tastypie.

Updates:

  • 07/10/2016: Upgraded to the latest versions of Python (v3.5.1), Django (v1.9.7), and django-tastypie (v13.3).

Project Setup

Either follow along below to create your sample Project or clone the repo from Github.

Create a new project directory, create and activate a virtualenv, install Django and the required dependencies:

Shell
$ mkdir django-tastypie-tutorial
$ cd django-tastypie-tutorial
$ pyvenv-3.5 env
$ source env/bin/activate
$ pip install Django==1.9.7
$ pip install django-tastypie==0.13.3
$ pip install defusedxml==0.4.1
$ pip install lxml==3.6.0

Create a basic Django Project and App:

Shell
$ django-admin.py startproject django19
$ cd django19
$ python manage.py startapp whatever

Make sure to add the app to your INSTALLED_APPS section in settings.py:

Python
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'whatever',
]

Add support for SQLite (or your RDBMS of choice) in settings.py:

Python
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'test.db'),
    }
}

Update your models.py file:

Python
from django.db import models


class Whatever(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

Create the migrations:

Shell
$ python manage.py makemigrations

Now migrate them:

Shell
$ python manage.py migrate --fake-initial

Note: The fake-initial optional argument is required if you have to troubleshoot the existing migrations. Omit if no migrations exist.

Fire up the Django Shell and populate the database:

Python
$ python manage.py shell
>>> from whatever.models import Whatever
>>> w = Whatever(title="What Am I Good At?", body="What am I good at? What is my talent? What makes me stand out? These are the questions we ask ourselves over and over again and somehow can not seem to come up with the perfect answer. This is because we are blinded, we are blinded by our own bias on who we are and what we should be. But discovering the answers to these questions is crucial in branding yourself.")
>>> w.save()

>>> w = Whatever(title="Charting Best Practices: Proper Data Visualization", body="Charting data and determining business progress is an important part of measuring success. From recording financial statistics to webpage visitor tracking, finding the best practices for charting your data is vastly important for your company’s success. Here is a look at five charting best practices for optimal data visualization and analysis.")
>>> w.save()

>>> w = Whatever(title="Understand Your Support System Better With Sentiment Analysis", body="There’s more to evaluating success than monitoring your bottom line. While analyzing your support system on a macro level helps to ensure your costs are going down and earnings are rising, taking a micro approach to your business gives you a thorough appreciation of your business’ performance. Sentiment analysis helps you to clearly see whether your business practices are leading to higher customer satisfaction, or if you’re on the verge of running clients away.")
>>> w.save()

Exit the shell when done.

Tastypie Setup

Create a new file in your App called api.py.

Python
from tastypie.resources import ModelResource
from tastypie.constants import ALL

from whatever.models import Whatever


class WhateverResource(ModelResource):
    class Meta:
        queryset = Whatever.objects.all()
        resource_name = 'whatever'
        filtering = {'title': ALL}

Update urls.py:

Python
from django.conf.urls import url, include
from django.contrib import admin

from django19.api import WhateverResource

whatever_resource = WhateverResource()

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api/', include(whatever_resource.urls)),
]

Fire Away!

  1. Fire up the server.
  2. Navigate to http://localhost:8000/api/whatever/?format=json to get the data in JSON format
  3. Navigate to http://localhost:8000/api/whatever/?format=xml to get the data in XML format

Remember the filter we put on the WhateverResource class?

Python
filtering = {'title': ALL}

Well, we can filter the objects by title. Try out various keywords:

  1. http://localhost:8000/api/whatever/?format=json&title__contains=what
  2. http://localhost:8000/api/whatever/?format=json&title__contains=test

Simple, right!?!

There is so much more that can configured with Tastypie. Check out the official docs for more info. Comment below if you have questions.

Again, you can download the code from the repo.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

Master Real-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

Master Real-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal.


Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

Keep Learning

Related Topics: api django projects web-dev