Django API Development, How to create API in Django

 

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.

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=>value pair.


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.


Step 1 :-

First we need to Install 3 mandatory packages:-

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

Step 2 :-

Create Django Project:-


Step 3:-

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


Comments