Create a Super Basic REST API with Django Tastypie (original) (raw)
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:
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:
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
- Fire up the server.
- Navigate to http://localhost:8000/api/whatever/?format=json to get the data in JSON format
- 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:
- http://localhost:8000/api/whatever/?format=json&title__contains=what
- 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
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
Master Real-World Python Skills
With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas: