Thursday, January 24, 2019

Generate API in python django

Welcome to best code practices of python ,
we will be discussing about how to create api in python in most effective way,

lets start rest framework package for creating api,
install restframework:
pip install djangorestframework


now ,
keep name in installedapp i.e. inside settings.py

now create new folder lets say "api" inside your app ,of which you want to create api.

inculde urls.py of api folder inside urls.py of the app

path('api/', include('hotel.api.urls')),

now, inside urls.py of api folder

from . import views
from rest_framework import routers
from django.urls import path, include

router = routers.DefaultRouter()
router.register('hotels', views.HotelViewSet)
router.register('city', views.HotelCitySet)
router.register('hotelname', views.HotelNameSet)
router.register('hotellandmark', views.HotelLandmarkSet)

urlpatterns = [
path('', include(router.urls)),
]

create serializers.py inside api folder

localhost:8000/api/
will show all apis available and you can click on those api to see json data send fron the system.


inside serializers.py

from rest_framework import serializers
from hotel.models import Hotels
from hotel.address.models import HotelAddress

class HotelSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Hotels
fields = ('name', 'owner_id_id', 'created_at', 'description')

class HotelCitySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = HotelAddress
fields = ('city',)

class HotelLandmarkSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = HotelAddress
fields = ('landmarks',)

class HotelNameSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Hotels
fields = ('name',)

here, write the fields that you want to send in api , when you need to send just single filed it should in tuple form so, comma is necessary.


Now inside views.py of api folder:

from hotel.api.serializers import HotelSerializer
from rest_framework import viewsets
from hotel.models import Hotels
from hotel.address.models import HotelAddress
from hotel.api.serializers import HotelCitySerializer
from hotel.api.serializers import HotelNameSerializer
from hotel.api.serializers import HotelLandmarkSerializer


class HotelViewSet(viewsets.ModelViewSet):
queryset = Hotels.objects.all().order_by('created_at')
serializer_class = HotelSerializer

class HotelCitySet(viewsets.ModelViewSet):
queryset = HotelAddress.objects.values('city')
serializer_class = HotelCitySerializer

class HotelNameSet(viewsets.ModelViewSet):
queryset = Hotels.objects.values('name')
serializer_class = HotelNameSerializer

class HotelLandmarkSet(viewsets.ModelViewSet):
queryset = HotelAddress.objects.values('landmarks')
serializer_class = HotelLandmarkSerializer



This is all we need to do for  creating and using apis,


Now this is all about simple form of API's  : what about a bit complex and more usefull :
For now here are some importatnt links:
for videos:
https://www.youtube.com/watch?v=XMu0T6L2KRQ&list=PLEsfXFp6DpzTOcOVdZF-th7BS_GYGguAS

Other Best reference:
https://blog.dbrgn.ch/2015/2/19/django-rest-framework-serializer-method-field/?fbclid=IwAR18H8bZtPwq82kAubcjOojfeTAaLro4ry2M5cuSek0KqFW2J9XxkC02vTQ

https://www.django-rest-framework.org/api-guide/filtering/?fbclid=IwAR1a50ov8abkG6BbYNLMbipe5si-kG-WuiPjXIie0LNHP92sbeUWkP9KELQ



Some other references that i have Obtained on my research are:




  • for basic of api :


  •  https://medium.com/the-andela-way/creating-a-django-api-using-django-rest-framework-apiview-b365dca53c1d
    • second one : https://codeburst.io/building-an-api-with-django-rest-framework-and-class-based-views-75b369b30396
    • https://www.django-rest-framework.org/tutorial/1-serialization/#introduction
    • https://www.django-rest-framework.org/api-guide/serializers/
    • http://www.tomchristie.com/rest-framework-2-docs/api-guide/serializers
    • https://medium.freecodecamp.org/nested-relationships-in-serializers-for-onetoone-fields-in-django-rest-framework-bdb4720d81e6
    • https://docs.djangoproject.com/en/2.1/howto/custom-model-fields/
    • https://www.quora.com/Do-I-really-need-serializers-in-Django-Rest-Framework-app
    • https://www.django-rest-framework.org/api-guide/filtering/?fbclid=IwAR3WQ3QfdN8Od66OflIxrgu7meE1AKLLvVso48G-qRnyWerD9Ts5YKUphyo
    • https://blog.dbrgn.ch/2015/2/19/django-rest-framework-serializer-method-field/?fbclid=IwAR0_-GFZMZxrJnwZI-_ALyidfvg40XZwhPSiGbaxgQrH51376bU5KdoXe2A
    • https://stackoverflow.com/questions/28078092/django-rest-framework-writable-nested-serializers

    • for best api guide:

    • https://www.django-rest-framework.org/api-guide/relations/

    • For many to many relation for  API :

    • https://www.reddit.com/r/django/comments/6yrh9k/drf_serialization_not_working_on_many_to_many/dms01dv/

    • More information:

    • https://stackoverflow.com/questions/17256724/include-intermediary-through-model-in-responses-in-django-rest-framework

    • Create customize many to many field in python  i.e. overriding normal many to many fields:

    • https://docs.djangoproject.com/en/2.1/topics/db/models/

    I am also going through them, soon i eill describe in best understandable way.


    OK Now lets Go through Detail From begning



    Lets create a normal serializer first for the address of hotel:


    in serializers.py

    class HotelAddressSerializer(ModelSerializer):
        class Meta:
            model = HotelAddress
            fields = [
                'city',            'state',            'country',            'address',            'contact1',            'contact2',            'latitude',            'longitude',        ]
    
    
    class HotelAmenitiesSerializer(ModelSerializer):
        # hotel=HotelSearchSerializer()    class Meta:
            model = HotelFacilities
            fields = [
                'name',            'image',
            ]
    
    
    
    
    Now lets use this two serializer in hotel serializer :
    
    
    
    
    class HotelSearchSerializer(ModelSerializer):
        galleries = HotelGallerySerializer(many=True, read_only=True)
        facilities = HotelAmenitiesSerializer(many=True, read_only=True)
        # hotel=HotelMiddleSerializer(many=True,read_only=True)    address = HotelAddressSerializer(read_only=True)
        # facilities = HotelMiddleSerializer(source='HotelFacilitiesMiddle', many=True)    # facilities = HotelMiddleSerializer(many=True)
        class Meta:
            model = Hotels
            fields = [
                'name',            'description',            'galleries',            'address',            'facilities',            # 'hotel'
            ]

    Here, hotelfacilities is in many to many relation with hotel:


    for this lets , create a customize relation wsing through so that api with including many to many relation can be generated :


    for that : inside models.py:

    class Hotels(models.Model):
        name = models.CharField(max_length=200)
        owner_id = models.ForeignKey(HotelOwner, on_delete=models.CASCADE)
    
        description = models.TextField(blank=True)
        is_active = models.BooleanField(default=False)
        # description = HTMLField()    created_at = models.DateTimeField(default=datetime.now, blank=True)
        facilities = models.ManyToManyField(HotelFacilities, through="HotelFacilitiesMiddle")
    
        def __str__(self):
            return self.name
    
        class Meta:
            verbose_name_plural = "Hotels"
    
    class HotelFacilitiesMiddle(models.Model):
        hotels = models.ForeignKey(Hotels,related_name="hotel", on_delete=models.CASCADE)
        hotelsfacilities = models.ForeignKey(HotelFacilities,related_name="hotelfacility", on_delete=models.CASCADE)
    
    
    
    
    now, in Views.py

    class HotelAddressViewSet(generics.ListAPIView):
        queryset = HotelAddress.objects.all().order_by('created_at')
        serializer_class = HotelAddressSerializer

    in urls.py

    path('hoteladdresslist/', HotelAddressViewSet.as_view(), name = 'hotelsearchlist'),
    
    
    path('initialhotellist/', HotelSearchViewSet.as_view(), name = 'hotelsearchlist'),
    
    





    Thank you for concerning, if any trouble occurs then please  comment below.





    No comments:

    Post a Comment