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 migratepython manage.py makemigrationspython manage.py runserver
7. Register database name in appname/admin.py
from .models import biodataadmin.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 serializersfrom .models import biodataclass Biodataserializers(serializers.HyperlinkedModelSerializer):class Meta:model = biodatafields = ('name', 'rollno', 'section', 'year')
from django.shortcuts import renderfrom .models import biodatafrom .serializers import Biodataserializersfrom rest_framework import viewsetsimport requestsclass 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, pathfrom rest_framework import routersfrom appname import viewsrouter = 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!