“Django REST_FRAMEWORK API endpoint and API response”

Mostafejur Rahman
3 min readOct 2, 2021

--

Let’s define our procedure below…

Steps 1: Install Django, rest_framework

$ pip install django
$ pip install djangorestframework

Step 2: Create a Django project “apisite” and app “api1”. Register the app and ‘rest_framework’ in apisite>settings.py

$ django-admin startproject apisite
$ python manage.py startapp api1
apisite>settings.pyINSTALLED_APPS = ['api1.apps.Api1Config',
'rest_framework',
....
]

Step 3: Create a model in api1>models.py for creating a superuser for the admin panel. Then migrate the model to DB.

api1>models.pyfrom django.db import models
from django.contrib.auth.models import User
from django.core.validators import RegexValidator
# Create your models here.class Item(models.Model):
"""This class will help us to create superuser in admin panel"""
access_token = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE)
Then use cmd...
$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py createsuperuser

Step 4: Now create a model for storing our contact info. like ‘name’, ‘phone’. In models.py

api1>models.pyfrom django.db import models
from django.core.validators import RegexValidator
class ContactList(models.Model):
"""This class takes data and store in db, using ORM concept"""
name = models.CharField(max_length=100)
phone_regex = RegexValidator(regex=r'^\+88\d{8,16}$', message='Phone number format +88xxxxxxx')
phone = models.CharField(validators=[phone_regex], max_length=14, blank=False)
def __str__(self):
"""This function return a string"""
return self.name
$ python manage.py makemigrations
$ python manage.py migrate

Steps 5: Add our ‘ContactList’ model in admin site admin.py

api1>admin.pyfrom django.contrib import admin
from .models import ContactList
# Register your models here.
admin.site.register(ContactList)

Step 6: Now work with rest_framework serializers. Create a file serializers.py in api1

api1>serializers.pyfrom rest_framework import serializers
from .models import ContactList
class ContactListSerializers(serializers.HyperlinkedModelSerializer): class Meta:
model = ContactList
fields = ['id', 'name', 'phone']

Steps 7: Now work with a view to see the endpoint of our API.

api1>views.pyfrom django.shortcuts import render
from .models import ContactList
from rest_framework import viewsets
from .serializers import ContactListSerializers
class ContactListViewSet(viewsets.ModelViewSet):
queryset = ContactList.objects.all().order_by('name')
serializer_class = ContactListSerializers

Steps 8: Create a urls.py in api1. To see the default view of our API

api1>urls.pyfrom django.urls import path, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'api', views.ContactListViewSet)
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
path('home/', views.DisplayContactList, name='display-contact-list'),
]

Steps 9: Add the urls.py in our ‘apisite’>urls.py

apisite>urls.pyfrom django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('api1.urls')),
]

Steps 10: Now run the server

$ python manage.py runserver

This is the endpoint of our API

Let's call our API using python-requests and display contact lists like ‘name’, ‘phone’.

Steps 1: Create a template directory and an HTML file like ‘home.html’ in the template directory inside our main folder. Now add the template in settings.py

apisite>settings.pyTEMPLATES = [
{
'DIRS': [os.path.join(BASE_DIR, 'template')],
....
}
]

Steps 2: Now send a python request with a function in our view.py and render it to home.html

api>views.pyimport requestsdef DisplayContactList(request):
response = requests.get("http://127.0.0.1:8000/api/").json()
return render(request, 'home.html', {'response': response})

Steps 3: Edit our HTML page

template>home.html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact List</title>
</head>
<body>
<h1>Contact list</h1>
<h3>
{% for i in response %}
{{i.name}}<br/>
{{i.phone}}<br/>
{% endfor %}<br/>
</h3>
</body>
</html>

Step 4: Run the server.

$ python manage.py runserver

That is the API result showing the name and phone number of the contact list…

I hope you can understand how it works. source code link is given below...

Github: https://github.com/mmrraju/django-rest_framework_api

--

--

Mostafejur Rahman
Mostafejur Rahman

Written by Mostafejur Rahman

I have completed my Bachelor's degree from Islamic University. I am interested in Software Engineering, Machine learning, Data Science, Cyber Security.

No responses yet