Create a Super Basic REST API with Django Tastypie (original) (raw)

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

Updates:

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:

Create a basic Django Project and App:

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

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

Update your models.py file:

Create the migrations:

Now migrate them:

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:

Exit the shell when done.

Tastypie Setup

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

Update urls.py:

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?

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.

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 »