Building an API Post End Point with DjangoRestFramework

philipokiokio

Philip Okiokio

Posted on February 11, 2021

Building an API Post End Point with DjangoRestFramework

First things first thank you for taking time out to work on your skill. It is hard work and it will eventually pay-up.


Hi, I am Philip, I am a backend eng./dev. I have read lots of books on Django that were a mix of sweet, sour, and annoying. I read them anyways, these books made learning Django relatively easy for me. Although I had not really worked on personal projects at that time, I worked hard on projects implemented in these books.

Django being a perfectionist way of building projects fast, seemed relatively easy to build full-stack apps, and with time we (learners, engineers) learn that API (Application Programing Interphase) are now best practices for the industry we love to be a part of.

So how do you write Django API? Well, we are lucky that the Django ecosystem is very large. Django has been around for 15 years and it has grown to be a family of developers sharing knowledge and tools via Reddit, and Stack Overflow. One known API solution for Django is called DjangoRestFramework.

Luckily, there was a book I read in December/ January called Django for APIs by William S. Vincent. He took time to really explain in depth the details of DjangoRest. I have written an epistle on Django and DjangoRest.

While I read the book, the code below

from rest_framework import generics
Enter fullscreen mode Exit fullscreen mode

was used to import the generic classes in making the views.
Here is its implementation in my code block.

class GeoListView(generics.ListCreateAPIView):
    queryset = Geospatial.objects.all()
    serializer_class = GeospatialSerializer
Enter fullscreen mode Exit fullscreen mode
generics.ListCreateAPIView 
Enter fullscreen mode Exit fullscreen mode

The code above had the ability to list all the data in the database and also create data and post( send/ Method=POST) it into the database. Here is what it looks like.

image.png

We can see a form at the bottom which can be used to send data into the database, now this form was an integral feature I needed to build. I toiled for hours and days which yielded little but I learned something very vital.

"While Documentations of some features could be understood by an experienced Engineer, it is important to write documentation with new users/engineers in mind".

Another important thing I learned is the act of searching google with the right keywords, this really was bane till some hours ago.
is its implementation in my code block.

class GeoListView(generics.ListCreateAPIView):
    queryset = Geospatial.objects.all()
    serializer_class = GeospatialSerializer
Enter fullscreen mode Exit fullscreen mode
generics.ListCreateAPIView 
Enter fullscreen mode Exit fullscreen mode

The code above had the ability to list all the data in the database and also create data and post( send/ Method=POST) it into the database. Here is what it looks like.

image.png

We can see a form at the bottom which can be used to send data into the database, now this form was an integral feature I needed to build. I toiled for hours and days which yielded little but I learned something very vital.

"While Documentations of some features could be understood by an experienced Engineer, it is important to write documentation with new users/engineers in mind".

Another important thing I learned is the act of searching google with the right keywords, this really was bane till some hours ago.

Now you might be asking why was I so bothered about a POST endpoint?
Great question, I was bothered because if you check the image above you would see a Geometry field (Ps. this has geospatial/GIS relation and I am not an authority on it), this field was not meant to be seen by the user of the form.

The Geometry field was meant to be automatically filled by the information gotten from the end-user. This means I needed a form to get the latitude, and longitude, then perform some logic to it before saving. In generic full stack Django, this can be handled with a forms.py and views.py but there is a different mode in DjangoRestFramework.

To get to the point, there is a create API method called

 generics.CreateAPI
Enter fullscreen mode Exit fullscreen mode

Now you might be asking why was I so bothered about a POST endpoint?
Great question, I was bothered because if you check the image above you would see a Geometry field (Ps. this has geospatial/GIS relation and I am not an authority on it), this field was not meant to be seen by the user of the form.

The Geometry field was meant to be automatically filled by the information gotten from the end-user. This means I needed a form to get the latitude, and longitude, then perform some logic to it before saving. In generic full stack Django, this can be handled with a forms.py and views.py but there is a different mode in DjangoRestFramework.

To get to the point, there is a create API method called

 generics.CreateAPIView 
Enter fullscreen mode Exit fullscreen mode

which is part of the rest framework generics class.
Now I had to make a big change in the serializers.py file. Below is the initial serializer.

class GeospatialSerializer(GeoFeatureModelSerializer):

    class Meta:
        fields = ['id','name','latitude','longitude','geometry']
        geo_field ='geometry'
        model = Geospatial_ddr

Enter fullscreen mode Exit fullscreen mode

From this serializer, it can be postulated that the model has just 4 fields while id (also known as the Primary Key (pk)) is autogenerated with every model. In this serializer, the geometry field is a geo-field and there is GeoFeatureModelSerializer that handles the GIS feature.

To create the APIView to get data, I had to write a new serializer.


class GeoFormSerializer(serializers.ModelSerializer):
    class Meta:
        fields = ['id','name','latitude','longitude']
        model= Geospatial_ddr
Enter fullscreen mode Exit fullscreen mode

So this code block takes care of the name, latitude, and longitude. Django's serialization framework provides a mechanism for “translating” Django models into other formats like JSON.

Now the views.py is where the work/business logic is. Here is what the class for CreateAPIView looks like.



class GisFormView(generics.CreateAPIView):
    serializer_class = GeoFormSerializer
    queryset = Geospatial.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data= request.data)
        serializer.is_valid(raise_exception=True)
        latitude= serializer.validated_data['latitude']
        longitude= serializer.validated_data['longitude']
        geom = Point(lat,long)
        serializer.validated_data['geometry']=geom
        serializer.save()
        return Response(serializer.data)



Enter fullscreen mode Exit fullscreen mode

Now, the create method makes it easy for me to access the data collected in the form, process it, and make adjustments based on the business logic before finally saving it into the database.
Here is what it looks like in the browser.

image.png
The form fields are now filled with data.

image.png
A post request can be made.
image.png
Here is what it looks like in the list field.

image.png

This is most likely a very surficial thing you can do with forms as an API, and there are more levels in complexity, validations, and the likes that can be done via the Django rest framework.

I hope that this was very informative, it is a lengthy read but I hope it was worth it for you. I hope to make a habit of writing about Django, Python Development, and industry.

Let me leave you with something someone tweeted some weeks back

Talent does not exist, Nothing is Given.

Thank you.

💖 💪 🙅 🚩
philipokiokio
Philip Okiokio

Posted on February 11, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related