How to Build a Polls API in Django Rest Framework?

Published On: 28/09/2022 | Category: Django

Hi Dev,

This is a short guide on how to build a polls api in django rest framework?. it's simple example of how to build a polls api with serializers in django. I explained simply about how to create a polls api using django rest framework. I explained simply step by step django rest framework polls api example. Let's see bellow example django rest polls api tutorial.

The official Django manual is the polls lesson. I wanted to demonstrate how easy it is to use the Django Rest Framework to turn it into a reliable API as a fun exercise.

In this tutorial we'll create a basic Django To Do app and then convert it into a web API using serializers, viewsets, and routers.

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example

Step 2: Create a App

Now we'll create a single app called polls to store a list of post names. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

python startapp polls

Step 3: Update

In this step we require to do two things in our file, One is our installed app name Add the below lines to your file:

Next, you need to add it in the file as follows:


Step 4: Create a Model

In this step we will require the database model for storing contacts.Open the polls/ file and add the following code:

import datetime

from django.db import models
from django.utils import timezone

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def was_published_recently(self):
        now =
        return now - datetime.timedelta(days=1) <= self.pub_date <= now

    def __str__(self):
        return self.question_text

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

Ok, all set. We can engender a migrations file for this change, then integrate it to our database via migrate.

python makemigrations
python migrate

Step 5: Update File

from django.contrib import admin

from .models import Question
from .models import Choice
Django Admin Interface:

Step 6: Creating the Serializers

In this step, we need to create Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data. Let’s start creating a serializer.

from rest_framework import serializers
from .models import Question

class QuestionSerializer(serializers.ModelSerializer):
    class Meta:
        fields = (
        model = Question

Step 7: Creating the Views

In this step, we need to create the views for performing the fetch record to the database.Open the polls/ file and add:

from rest_framework import viewsets

from . import models
from . import serializers

class QuestionViewSet(viewsets.ModelViewSet):
    queryset = models.Question.objects.all()
    serializer_class = serializers.QuestionSerializer

Step 8: Creating URLs

In this section, we need a file within the apis app however Django doesn't create one for us with the startapp command. Create polls/ with your text editor and paste below code.

from django.urls import path

from .views import QuestionViewSet
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register('', QuestionViewSet, basename='questions')
urlpatterns = router.urls

Next, we will require the modify the your root preoject folder lets update the file.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('api/', include('polls.urls')),

Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python runserver

Next, go to the address with a web browser.

I Hope It will help you....