Django API Development, How to create API in Django

0




API means application programming interface, it is used to communicate dynamic data from one application to another application.


API provides a modern design pattern to develop applications means we can create one separate application to create an API that can be consumed into another application, another application can be the same technology or different technology.


This means we can create Django REST API that can be used in android, ios, REACT, NODE, Java, .NET, and PHP.


What does API provide?


It provides a Restful URL to implement functionality using different HTTP Methods?


1)   GET:-   It is used to fetch the record from the server


2)  POST:-  It is used to insert the record into the server


3)   PUT:-   It is used to update the record into the server


4)  Delete:-  It is used to delete the record into the server


5)  Patch:-  It is used to partially update the content of the server


What type of Data API return:-


API return JSON type data, JSON means Javascript object notation, it contains data using key=>vaue pair.

you can enter this URL then it shows JSON Format Data

https://shivaconceptsolution.com/webservices/showreg.php


Single row:-

{"rno":1001,"name":"xyz"}  // single row return

Multiple rows:-

{

    {"rno":1001,"name":"xyz"}, 

    {"rno":1002,"name":"mno"} ,

     {"rno":1003,"name":"abc"}  

]

}


How to TEST API?

If you want to test API before implementation then you can prefer many API Testing Tools

1) POSTMAN

2) SWAGGER


Create API using Django-REST Framework:-


Django REST framework is a powerful and flexible toolkit for building Web APIs.


First Install three mandatory packages:-

pip install djangorestframework
pip install markdown       # Markdown support for the browsable API.
pip install django-filter  # Filtering support


Step2nd:-


Create Django Project:-


Step3rd:-

go into settings.py and following changes:-


INSTALLED_APPS = [

    'rest_framework',

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

]


REST_FRAMEWORK = {

    # Use Django's standard `django.contrib.auth` permissions,

    # or allow read-only access for unauthenticated users.

    'DEFAULT_PERMISSION_CLASSES': [

        'rest_framework.permissions.AllowAny'

    ]

}


Step4th:-



from django.contrib import admin
from django.urls import path,include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ['url', 'username', 'email', 'is_staff']

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
router = routers.DefaultRouter()
router = routers.SimpleRouter(trailing_slash=False)
router.register(r'users', UserViewSet)
           
urlpatterns = [
    path('', include(router.urls)),
    path('admin/', admin.site.urls),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]




Open  POSTMAN Tools if your new then search on google and install it then test from it/


Check GET 

http://127.0.0.1:8000/users

Check POST

http://127.0.0.1:8000/users


How to create separate app form django-api

1)  create an app under the same project

    python manage.py startapp appname

2)  create serializers.py under app with the following code

  from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ['url', 'username', 'email', 'groups']


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ['url', 'name']    


3)  create views.py code 

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework import permissions
from tutorial.serializers import UserSerializer, GroupSerializer

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
   

class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
      

4)  edit project urls.py

from django.contrib import admin
from django.urls import path,include
from rest_framework import routers
from tutorial import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

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


5)  edit settings.py

INSTALLED_APPS = [
    'tutorial',
    'rest_framework',
  ...
]

REST_FRAMEWORK = {

    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',

    'PAGE_SIZE': 10

}


6)   first implement migrate command and runserver


7)  type the following URL


    

Open  POSTMAN Tools if your new then search on google and install it then test from it/


Check GET 

http://127.0.0.1:8000/users

Check POST

http://127.0.0.1:8000/users



to download complete code download here 

https://github.com/shivaconceptsolution/django-rest-api-example



How to create REST Full API using Custom Model:-


Create Project and modify settings.py


INSTALLED_APPS = [


    'tutorapp',

    'rest_framework',

   .

]


REST_FRAMEWORK = {

    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',

    'PAGE_SIZE': 10

}


Modify Urls.py under project Urls:-

from django.contrib import admin

from django.urls import path,include

from rest_framework import routers

from tutorapp import views

router = routers.DefaultRouter()


router.register(r'tutors', views.TutorViewSet)


           

urlpatterns = [

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

    path('admin/', admin.site.urls),

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

]


Create app and create the model:-

from django.db import models

from django.db import models

class TutorReg(models.Model):

    password = models.CharField(max_length=10)

    mobileno = models.CharField(max_length=10)

    fname = models.CharField(max_length=20)

    def __str__(self):

        return "Password is "+self.password + " Mobile no is "+self.mobileno + " fname is "+self.fname


Create serializers.py under app

from .models import TutorReg

from rest_framework import serializers

class TutorSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:

        model = TutorReg

        fields = ['password', 'mobileno','fname']



create views.py and create viewSet


from .models import TutorReg

from rest_framework import viewsets

from rest_framework import permissions

from tutorapp.serializers import TutorSerializer


class TutorViewSet(viewsets.ModelViewSet):

    """

    API endpoint that allows users to be viewed or edited.

    """

    queryset = TutorReg.objects.all()

    serializer_class = TutorSerializer



Start the server and check URLs 

http://127.0.0.1:8000/tutors/


How to consume RESTFULL API:-

1)  create project ad create app

2) pip install requests

3)  Write code on app/views.py

import requests

    def index(request):

response = requests.get('http://127.0.0.1:8000/tutors')

tutor = response.json()

return render(request,"userapp/index.html",{'data':tutor})


   

4)  create index.html file and display it.

 {% for k in data %}

    {{k.password}}  | {{k.fname}} | {{k.mobileno}}  <hr>
    {%  endfor %}
</section>


   python manage.py runserver 8086 

Click to download project:-

Download




Post a Comment

0Comments

POST Answer of Questions and ASK to Doubt

Post a Comment (0)