Tuesday, January 16, 2018

Django REST API using code first approach

In the previous post we have set up the application with JWT authentication.

In this post we will learn about how to use a code first approach to create api through which you can add, edit, delete and read the data in the table.
Given below are the steps -
1) Create a model with name and desc as text fields.


class mytable(models.Model):
    name=models.CharField(max_length=200)
    desc=models.TextField()


2) Migrate the changes to the database by
    a) Cerate the list of changes to be migrated to the database using the command - python manage.py makemigrations
    b) Add the changes to the table - python manage.py migrate
   
3) Create a file called serializers.py inside the app and add the code below -

   
class mytables(serializers.ModelSerializer):
        class Meta:
            model=mytable
            fields=('name','desc')
    


4) Next we need to add views to define the web api in views.py:
    a) Add the below imports into the code -
        from django.shortcuts import render
        from azure.servicebus._http import HTTPResponse
        from .models import *
        from .serializers import *
        from rest_framework.views import APIView
       
    b) Add the below code for reading the data in the table -

   
        class my_list(APIView):
            def get(self,request,format=None):
            dat=mytable.objects.all() #to get all the data from the table
            serialized=mytables(dat,many=True) #to serialize the data
            return Response(serialized.data) #to return the serialized data

   
    c) To insert data into the table -
        @api_view(('POST','PUT'))
        def test_insertmod(request):
            try:
                indata=request.POST.get('name')
                indesc=request.POST.get('desc')
                inkey=request.POST.get('key')
                testinstance=mytable.objects.create(id=inkey,name=indata, desc=indesc)
                return Response('Successfully inserted')
            except Exception as e:
                print(e)
                return(e)

   
    d) To update the data in the table
   
   
        @api_view(('POST','PUT'))
        def test_insertmod(request):
            try:
                indata=request.POST.get('name')
                indesc=request.POST.get('desc')
                inkey=request.POST.get('key')
                testinstance=mytable.objects.create(id=inkey,name=indata, desc=indesc)
                return Response('Successfully inserted')
            except Exception as e:
                print(e)
                return(e)

   
    e) To delete the data in the table -
   

@api_view(('POST','PUT'))
def test_deletemod(request):
    try:
        indata=request.POST.get('name')
        testinstance=mytable.objects.get(name=indata)
        testinstance.delete()
        return Response('Successfully deleted')
    except Exception as e:
        print(e)
        return(e)



5) Now that we have the views in place, we need to make the urls so that the views can be accessible -
    url(r'^mylist/', views.my_list.as_view()),
    url(r'^modinsert/',views.test_insertmod),
    url(r'^modupdate/',views.test_updatemod),
    url(r'^moddelete/',views.test_deletemod),


Now that we are done, start the django project and use the postman in chrome to test it -

Please ensure that you have the url authorized using the link http://127.0.0.1:8000/webs/auth-jwt/ and authenticating the api using the userid and password.

1) To insert data into the table - http://127.0.0.1:8000/webs/modinsert/

   

   

2) To read the data in the table use the url - http://127.0.0.1:8000/webs/mylist/


3) To update the data in the table use the url - http://127.0.0.1:8000/webs/modupdate/





4) To delete a key in the table use the link - http://127.0.0.1:8000/webs/moddelete/



   

No comments:

Post a Comment