Categories
Python

Django REST Framework: Quick Introduction

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:

Add to Installed Apps:

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:

We will create a class based view for allowing REST access to this Model:

Add to urls.py to add URL handlers for the view:

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:

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:

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.