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 manage.py startapp polls

Step 3: Update setting.py

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

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

example/settings.py
....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'polls',
]

Step 4: Create a Model

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

polls/models.py
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 = timezone.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 manage.py makemigrations
python manage.py migrate

Step 5: Update admin.py File

polls/admin.py
from django.contrib import admin

from .models import Question
from .models import Choice

admin.site.register(Question)
admin.site.register(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.

polls/serializers.py
from rest_framework import serializers
from .models import Question


class QuestionSerializer(serializers.ModelSerializer):
    class Meta:
        fields = (
            'id',
            'question_text',
            'pub_date',
        )
        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/views.py file and add:

polls/views.py
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 urls.py file within the apis app however Django doesn't create one for us with the startapp command. Create polls/urls.py with your text editor and paste below code.

polls/urls.py
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 urls.py your root preoject folder lets update the file.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    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 manage.py runserver

Next, go to the http://127.0.0.1:8000/api/ address with a web browser.

I Hope It will help you....