DRF - what is that?


It's a simplifier for creating API using Python's Django framework.

You can check my short comparison between different type of Django-supported API frameworks here

Django Rest Framework example project

Initially, I wanted to make my own sample Django REST Framework project that will be used in this tutorial.

Then I've thought to myself- "There must be a better way" (quoting Uncle Bob ^^) - so I've found a repository at GitHub with already predefined simple logic for maintaining TODO-list as an REST-api.

Check it here.

DRF Environment setup

Check out my prepared GitHub-Gist with a simple Linux-commands that you use to prepare your environment HERE.

Checking out the source code of sample project for bulk todo-elements creation.

So first things first - let's check if our code will enable use creation of more than one element using API at once. Let's make a POST request with a list of todos:

    {"name": "TEs<t2"}

The output of it is :

    "non_field_errors": [
        "Invalid data. Expected a dictionary, but got list."

Means - no. No luck this time :) Let's un-release this and make a bulk of TODOs per one request.

List Serializer

I'm writing this post-heading information after about 3 hours. I've struggled to work with List-Serializer. I tried to use it in a "django" way - but for now, it's beyond my perception. I've found a solution at stackoverflow that after few adoption tricks started to work properly. It's not perfect - but quoting "Done is better than perfect" - I consider it a work-in-progress solution.

I might go back to this and try to investigate how it should be done in more "Django" way

Checkout code:

class TodoBatchAPIView(ListCreateAPIView):
    API endpoint that allows multiple members to be created.
    queryset = Todo.objects.none()
    serializer_class = TodoSerializer

    def get_queryset(self):
        queryset = Todo.objects.all()
        return queryset

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data, many=isinstance(request.data, list))
        todo_created = []
        for list_elt in request.data:
            todo_obj = Todo.objects.create(user=request.user, **list_elt)
        results = Todo.objects.filter(id__in=todo_created)
        output_serializer = TodoSerializer(results, many=True)
        data = output_serializer.data[:]
        return Response(data)

and in urls.py:

url(r'^batch/$', TodoBatchAPIView.as_view(), name="batch"),

Thanks :)

Hope you find this solution valuable.

I for sure will use it in my Biking-Endorphines project.

Please comment and feel free to post your solution to this problem!


comments powered by Disqus