How to Create a API using Django Rest Framework?

Published On: 25/07/2022 | Category: Django Python


Hi Dev,

Here, I will show you how to create a api using django rest framework. We will look at example of django rest api example. you will learn django rest framework post example. I would like to show you django rest api tutorial.

Here i explained Django REST Framework is a wrapper over default Django Framework, basically used to create APIs of various kinds. There are three stages before creating a API through REST framework, Converting a Model’s data to JSON/XML format (Serialization), Rendering this data to the view, Creating a URL for mapping to the viewset.

While Django does a lot of heavy lifting by connecting it’s models to the database, serializing those models into a JSON format is still a big challenge. DRF complements Django by providing a means of converting it’s models to a REST-full format.

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
python manage.py startapp rest_api
Step 3 : Install a Django REST Framework

First of all let’s install django and djangorestframework which are the necessary Python libraries.

pip install djangorestframework
Step 4 : Update setting.py

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

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

settings.py
....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_api',
]
Step 5 : Database Setup

Next step, we will modify the settings.py file and update the database settings to configure the mydb database:

settings.py
DATABASES = {  
    'default': {  
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'example',  
        'USER':'root',  
        'PASSWORD':'root',  
        'HOST':'localhost',  
        'PORT':'3306'  
    }  
}  
Step 6: Create a Model

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

rest_api/models.py
from django.db import models

# Create your models here.

class Blog(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    

After creating these model, you need to create migrations using the following command:

Step 7 : Create a Migrations
python manage.py makemigrations

After successfully run the above command go to the rest_api/migrations/0001_initial.py

rest_api/migrations/0001_initial.py
# Generated by Django 3.1.7 on 2022-07-22 13:55

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Blog',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=100)),
                ('description', models.TextField()),
            ],
        ),
    ]

Next, you need to migrate your database using the following command:

python manage.py migrate
Step 8 : 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.

rest_api/serializers.py
from rest_framework import serializers

from core.models import Blog

class BlogSerializer(serializers.ModelSerializer):
    class Meta:
        model = Blog
        fields = ('title', 'description')
Step 9 : Creating the Views

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

rest_api/views.py
from rest_framework import viewsets

from core.serializers import BlogSerializer
from core.models import Blog


class BlogViewSet(viewsets.ModelViewSet):
    queryset = Blog.objects.all()
    serializer_class = BlogSerializer
Step 10 : Creating URLs

In this section, we’ll create the urls to access our views.Go to the urls.py rest_api/urls.py file and update it as follows:

rest_api/urls.py
from django.urls import include, path

from rest_framework import routers

from core.views import BlogViewSet

router = routers.DefaultRouter()
router.register('blogs', BlogViewSet)

urlpatterns = [
    path('', include(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('', include('rest_api.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://localhost:8000/blogs/ address with a web browser.

I Hope It will help you....