This tutorial will describe how to create and serve a simple REST API using Django. Django is a framework for creating web backends using Python. It’s very fast, and if you are familiar with Python it is very easy to get started with.
Pre-requirements
Before you start, you will need to install Python, Pip and Virtualenv. If you are on Windows, I suggest you also get a third party command line tool, like Bash.
You will also need an editor. For a customisable, lightweight, multilanguage IDE, a good alternative is Atom. If you want a more out-of-the-box polished solution with a more extensive set of features, you can use JetBrains’ Python-only editor PyCharm. The ultimate version is available for free if you register a JetBrains account with your student email address.
Step 1 – Project setup
Open your terminal and navigate to the folder you want your project to be located in, and perform the following steps.
Create the project directory
mkdir tutorial
cd tutorial
Create a virtualenv (this is to isolate our package dependencies locally)
Note: If you’re on Windows, exchange the word ‘bin’ in the following command with ‘Scripts’.
virtualenv env
source env/bin/activate
Install Django and Django REST framework into virtualenv
pip install django
pip install djangorestframework
Set up a new project with a single application
Note the trailing ‘.’ character in line 2.
cd ..
django-admin.py startproject tutorial .
cd tutorial
django-admin.py startapp quickstart
cd ..
Now it’s time to sync your database for the first time:
python manage.py migrate
You should now have a file in your parent folder called db.sqlite3
, which is your SQL database.
We’ll now create an admin user to restrict access to your REST API:
python manage.py createsuperuser
Note: If you’re on Windows, and this does not work, try adding winpty
at the front of the command.
Input admin
as username and password123
as password, leave the email field blank.
That is your project set up, next we have some coding to do. Open up your project in your preferred IDE.
Step 2 – Programming
Serializers
First, we’re going to define some serializers. These describe how your models are represented. Create a new file inside the tutorial/quickstart
folder called serializers.py
, and fill it with the following code:
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ('url', 'name')
Views
Next, we’ll make some views. Open and edit the views.py
file inside the tutorial/quickstart
folder.
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
URLs
Our REST API need URLs so that we can reach our database. They are defined in tutorial/urls.py
.
from django.conf.urls import url, include
from rest_framework import routers
from tutorial.quickstart import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
Settings
Finally we have to change and add a couple of settings, intuitively found in tutorial/settings.py
.
INSTALLED_APPS = (
...
'rest_framework',
)
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAdminUser',
],
'PAGE_SIZE': 10
}
That’s it, you’re done.
Step 3 – Testing your API
First, we need to start our server.
python manage.py runserver
You can now access your API, either by using tools like curl
, or by redirecting your browser to localhost:8000
. Here you can login with the previously set username and password.
At the /users/
URL you can view and edit all your users. Change the GET format to JSON to get raw data.
A corresponding view for groups is found at /groups/
.