Okay, so you know how cool Django is? Well, Django Rest Framework brings the Django like simplicity in building REST APIs.
Installation
Use pip to install:
1 2 3 |
pip install djangorestframework pip install markdown # Markdown support for the browsable API. pip install django-filter # Filtering support |
Add to Installed Apps:
1 2 3 4 |
INSTALLED_APPS = ( ... 'rest_framework', ) |
ModelViewSet: Doing The Magic
ModelViewSet takes a Model and automates the required REST access to it. Let’s see how simple it is.
We have a Model like this:
1 2 3 4 5 |
from django.db import models class Photo(models.Model): path = models.CharField("Path", max_length=250) title = models.CharField("Title", max_length=250) |
We will create a class based view for allowing REST access to this Model:
1 2 3 4 5 6 7 8 9 10 11 |
from rest_framework import viewsets, routers from api.models import * class PhotoViewSet(viewsets.ModelViewSet): model = Photo # Register the viewset api_router = routers.DefaultRouter() api_router.register(r'photo', PhotoViewSet) |
Add to urls.py to add URL handlers for the view:
1 2 3 4 5 6 7 8 |
from django.conf.urls import patterns, include, url from api.views import api_router # Import the api_router defined above urlpatterns = patterns( '', url(r'^', include(api_router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ) |
Now run syncdb and runserver commands from manage.py. If you visit: localhost:8000 (or whatever the address of the development server on your machine), you should be able to see the api root. In the URLConf defined above, we should be able to access the Photo model on “/photo”. Use a REST client to try it out.
Authentication
Django Rest Framework supports multiple authentication systems. Here, we shall see how we can enable basic http auth to the REST APIs.
Add this to settings.py:
1 2 3 4 5 6 |
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ) } |
That’s it. Now we have the Django Auth system hooked into Django Rest Framework. Any user registered with the default django auth is a now valid user for the REST APIs as well. But how do we find the authenticated user? It’s simple as always. You can grab “request.user” for the user data and “request.auth” for extra auth data (specially when working with oauth implementation).
Let’s see how we can use in the class based views we demonstrated above:
1 2 3 4 5 6 7 8 9 10 |
from rest_framework.response import Response class ComplementViewSet(viewsets.ModelViewSet): model = Complement def get_queryset(self): print self.request.user return Complement.objects.all() def list(self, request, *args, **kwargs): return Response({"name": str(request.user)}) |
Here we have overridden the list() method to demonstrate how to use the request object. If any user tries to access without authenticating, the request.user will be set to AnonymousUser. If authenticated, it will be set to the authenticated user.
By overriding the methods of a ModelViewSet, we can customize the response based on authentication status. We can also use Permission & Throttling policies for easier control. I’ll try to write about those in future blog posts.