DEV Community

Apcelent
Apcelent

Posted on

How to create REST API using Django REST Framework

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

Alt text of image

Installation

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:

django-admin.py startproject samplenote .
cd samplenote
django-admin.py startapp note

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

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    #app
    'note',

    #rest_framework
    'rest_framework',
]

Model

Edit models.py 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(default=timezone.now)
    created_by = models.CharField(max_length=50, blank=True, null=True)
    priority = models.IntegerField(validators=[MinValueValidator(1),
                                       MaxValueValidator(5)])

Now Create and apply schema migration by executing following:

python manage.py makemigrations
python manage.py 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 note_api.py 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')

Viewset

Viewsets are classes which provide functionality of set of views. Create a NoteViewSet class based on ModelViewSet in note_api.py 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 manage.py runserver

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

http://127.0.0.1:9000/api/notes/

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!

The article originally appeared on Apcelent Tech Blog.

Top comments (0)