Django REST Framework AS Fast AS Possible

Robin Francis
Sep 2, 2018 · 4 min read

With many people moving to something like GraphQL, I still like django_rest_Framework for its simplicity and its power, also you get a really simplistic human readable view, which you can access via you browser.

So there are few different parts of Django REST Framework, I’ll cover them as fast as possible and also make it super simple as well.

I do assume you know the basics of web development using django.

So lets dive right in, shall we?

We are gonna create a simple Job posting app, with just one view and model, this is to keep things super simple

First we’ll create a virtualenv

$ mkvirtualenv restTuts
$ workon restTuts
$ pip install django==1.8 django-rest-framework

Next, we obviously need to create our django project

$ django-admin startproject jobHunt

next we create our app, jobs which will list all the jobs..

$ django-admin startapp jobs

Next, we add the app to our project, by editing jobHunt/settings.py

INSTALLED_APPS = [
.....
#app listing end here
# third party apps
'rest_framework',
# Personal apps
'jobs',
]

Next, we create our first model in our jobs app, jobs/models.py

from django.db import models# Create your models here.
class Jobs(models.Model):
title = models.CharField(max_length=255, null=False)
company = models.CharField(max_length=255, null=False)
salary = models.DecimalField(max_digits=10,decimal_places=2)
def __str__(self):
return 'Rs {} salary for {} role at {}'.format(self.salary, self.title, self.company)

Serialize IT!

Now, we need to serialize our models..

Whats serialize you ask? Its basically converting data into a simple format that can be easily stored and read , here we’ll go with JSON, which is the format by default..

create a new file, jobs/serializers.py

from rest_framework import serializers
from .models import Jobs
class JobsSerializer(serializers.ModelSerializer):
class Meta:
model = Jobs
fields = ("title", "company", "salary")

We need to View it Right?

from .models import Jobs
from .serializers import JobsSerializer
from rest_framework import generics
# Create your views here.
class ListJobsView(generics.ListAPIView):
queryset = Jobs.objects.all()
serializer_class = JobsSerializer

The first two lines just import our Model and our JobsSerializer

The third line imports the generics module from rest_framework, this gives us bunch of view class which we can extend to get really nicely formatted views for our rest models.

Geenric Views are alaways class views, except for few exceptions.

So we just create our view class extending ListAPIView, this view will be to list all the content only for Jobs model. Which means the HTTP methods available are HEAD, OPTIONS, GET only!

Next, we form a queryset using django’s built in methods. Querysets are objects which return the result of a DB query done by django behind the scenes for you. Its got a really cool interface, so check it out on django docs.

Next we pass in the serializer class to the variable serailizer_class

Make sure you don’t change this name as its used by rest_framework to use the appropriate serializer class.

Now we need to hook our views to appropriate urls,

This is a two step process, first we need to add our base url, which will redirect to our api sections,

So go to jobHunt/urls.py

from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'api/(?P<version>(v1|v2))/',include('jobs.urls')),
]

include(‘url_path_as_string’), is used for including complete set of urls in a different app, its how django’s been working for a long time, so we’ll leave it like this

(?P<version>(v1|v2)), helps us pass different versions, more on that a little later. You can ignore it for now and keep it simple as

url(r'api/',include('jobs.urls')),

Next we need to create our urls.py for our jobs app at jobs/urls.py

from django.conf.urls import url, include
from django.contrib import admin
from . import views
urlpatterns = [
url(r'jobs/',views.ListJobsView.as_view(),name="all-jobs"),
]

we import our views and we provide it a namespace of “all-jobs”, which means to get back to this url from our django app code, we can simply use “all-jobs” as a reverse-url parameter.

Thats it, we are done setting up our REST API

All that needs to be done is to makemigrations and then migrate our models, so..

$ ./manage.py makemigrations
$ ./manage.py migrate
$ ./manage.py runserver

next, go to our browser to the following address, assuming you are developing on your local machine

localhost:8000/api/v1/jobs

or if you went with my simpler version

localhost:8000/api/jobs

And you should see something like this

If you don’t see any values like here, don’t freak out. You need to create them.

You can do that in two ways

  1. use the ./manage.py shell and create new objects using models.Jobs.objects.create(title=”value”,company=”value”,salar=val)
  2. create a super user using, ./manage.py createsuperuser, and then login at localhost:8000/admin.py. Then add new values

Cool, so thats a super duper uber simple Intro tutorial to django_rest_framework, that even a child can understand and I hope it was as fast as possible!

Next time, we’ll cover POST and PUT requests as well.

Robin Francis

Written by

Here lies the diary of an autodidactic polymath. Who loves to write articles, on software development, music, cooking, film-making, art, and learning hacks.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade