How to create REST API using Django REST Framework

Django rest framework is a python toolkit to create REST APIs for django applications.


Create a virtual environment for our project and then install Django and Dajngo REST Framework

sudo pip install virtualenv
virtualenv venv
source venv/bin/activate
pip install Django==1.9
pip install djangorestframework==3.6.3

After django installation, Create a project samplenote. Inside that project we create an app note: startproject samplenote .
cd samplenote startapp note

Update file in samplenote folder to include newly added apps - note and rest_framework.



Edit file in note app. Add a Note model class with title, description, created date, created by and priority fields.

from django.db import models
from django.utils import timezone
from django.core.validators import MaxValueValidator, MinValueValidator
# Create your models here.
class Note(models.Model):
    title = models.CharField(max_length=100)
description = models.CharField(max_length=400)
created_at = models.DateTimeField(
created_by = models.CharField(max_length=50, blank=True, null=True)
priority = models.IntegerField(validators=[MinValueValidator(1),

Now Create and apply schema migration by executing following:

python makemigrations
python migrate

Creating serializer

Serializers are used to convert data from different formats like JSON, XMl to complex data types like querysets and model instances and vice versa.

Create a Note serializer based on Node model created earlier. This serializer is defined in file of note app.

from rest_framework import serializers
from .models import Note
class NoteSerialiser(serializers.HyperlinkedModelSerializer):
    class Meta:
model = Note
fields = ('id', 'title', 'description', 'created_at', 'created_by', 'priority')


Viewsets are classes which provide functionality of set of views. Create a NoteViewSet class based on ModelViewSet in file of note app.

from rest_framework import viewsets
class NoteViewSet(viewsets.ModelViewSet):
    queryset = Note.objects.all()
serializer_class = NoteSerialiser

Run the server

After setting up serializers and viewsets, run the server:

python runserver

To get a list of all notes, send a GET request to following URL

To add a new note, send a POST request to the same URL with data in following format in body part of the request.

"created_at": "2017-08-17 00:00",
"created_by": "v",
"description": "sample notes from api",
"priority": 1,
"title": "sample note from api"

The source code can be found on github

Hope the article was of help!

This article was originally published in Apcelent