TechAE Blogs - Explore now for new leading-edge technologies

TechAE Blogs - a global platform designed to promote the latest technologies like artificial intelligence, big data analytics, and blockchain.

Full width home advertisement

Post Page Advertisement [Top]

How To Render REST API On Django

How To Render REST API On Django

Serialization

The process of querying and converting tabular database values into JSON or another format

is called serialization. When you’re creating an API, correct serialization of data is the major challenge.

Here we use serializers to build a REST Django API.

Django Project Setup

Make a folder and open cmd from that folder. Use the following commands step by step


1. To create isolated python environments


python -m venv venv


2. To activate the virtual environment


venv\Scripts\activate


3. Enter the Django command after you've established and activated a virtual environment


pip install django


4. To make a project directory


django-admin startproject projectname


5. Go to the project directory


cd projectname


6. Create the Django App


python manage.py startapp appname


7. Start the server


python manage.py runserver


8. Open the project


code .

Build a REST API with Django REST Framework

Create a model in the database that the Django ORM will manage. Run the following commands

 

1. Start the Django server


python manage.py migrate


2. Create Django Django admin


python manage.py createsuperuser

python manage.py runserver


3. Check admin on


http://127.0.0.1:8000/admin


4. Register your app in projectname/settings.py


INSTALLED_APPS = [

    'appname.apps.AppnameConfig',

    ... # Leave all the other INSTALLED_APPS

]


5. Create a Model in models.py


class biodata(models.Model):
    name = models.CharField(max_length=60)
    rollno = models.IntegerField()
    section = models.CharField(max_length=1)
    year = models.IntegerField()

    def __str__(self):
        return self.name


6. Migrate model on Admin


python manage.py migrate
python manage.py makemigrations
python manage.py runserver


7. Register database name in appname/admin.py


from .models import biodata

admin.site.register(biodata)


Also, add some data manually to Django admin http://127.0.0.1:8000/admin. So that it will be viewed on the front end.


8. Setup Django REST Framework. Run the following command on Terminal


 pip install djangorestframework


9. Adding REST Framework in settings.py


 INSTALLED_APPS = [

    # All your installed apps stay the same

    ...

    'rest_framework',

]


10. Create a serializers.py file in the appname/serializers.py and make a class in it where the bioData model will be serialized


from rest_framework import serializers
from .models import biodata


class Biodataserializers(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = biodata
        fields = ('name', 'rollno', 'section', 'year')

11. Make a class in views.py file after importing the serializer file


from django.shortcuts import render
from .models import biodata
from .serializers import Biodataserializers
from rest_framework import viewsets
import requests

class BiodataViewSet(viewsets.ModelViewSet):
    queryset = biodata.objects.all().order_by('rollno')
    serializer_class =  Biodataserializers  


12. Command to install requests


pip install request


13. Include your app name in the projectname/urls.py


from django.urls import include

path( '' , include( 'appname.urls'))


14. Register database in appname/urls.py


from django.urls import include, path
from rest_framework import routers
from appname import views

router = routers.DefaultRouter()
router.register(r'biodata', views.BiodataViewSet)

urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),

]


And here, the rest API is created. Check by using the command


python manage.py runserver

Render API on the frontend with Core Django

Now, we have created our REST API, now we want to check it on our frontend.


1. Add def function in views.py file


def biodata(request):
    responsedata = requests.get('http://127.0.0.1:8000/biodata/').json()    
    return render(request, 'data.html', {'responsedata': responsedata})


2. In App folder make the templates folder and create the file name appname/templates/data.html


{% for i in responsedata %}
<h1>{{i.rollno}}</h1>
<br />
<p>{{i.name}}</p>
<br />
<p>{{i.section}}</p>
<br />
<p>{{i.year}}</p>

{% endfor %}


3. Adding path to appname/urls.py


urlpatterns = [
      path('', include(router.urls)),
      path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
      path('data/', views.biodata, name="data"), 
]


4. View your API on the server by using the command


http://127.0.0.1:8000/data/

Thank you for reading!

So we found a clear method to create REST API using Django and then rendering on our frontend.

If you found this article useful, stay tuned for more articles on Django.

Cheers!

No comments:

Post a Comment

Thank you for submitting your comment! We appreciate your feedback and will review it as soon as possible. Please note that all comments are moderated and may take some time to appear on the site. We ask that you please keep your comments respectful and refrain from using offensive language or making personal attacks. Thank you for contributing to the conversation!

Bottom Ad [Post Page]