DEV Community

Cover image for Working with Django Rest Framework(DRF).
JeffUbayi
JeffUbayi

Posted on

Working with Django Rest Framework(DRF).

The first step is to install Django Rest-Framework and then create a new apis app.
The source code is available on my Github.

All of our API information will be routed through here. Even if we had multiple apps in our project, we’d still only need a single apis app to control what the API does.

      (todo) $ pipenv install djangorestframework==3.10.3
      (todo) $ python manage.py startapp apis

Add both the apis app and rest-framework to our installed apps.
We also add Permissions so that only logged in users could access the API.

#todo_project/settings.py

INSTALLED_APPS = [
    ...
    'rest_framework',
    'apis.apps.ApisConfig',
    'todos.apps.TodosConfig',
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ]

As tradition,A Django app needs a dedicated url, view, and template to translate information from that database onto a webpage.While in DRF,we just need url,view and serializer.

The url controls the access to the API endpoints,views controls the logic of the data being sent and serializers does the magic of converting our information into a suitable format(JSON,XML).

A normal webpage requires HTML, CSS, and JavaScript (usually). But our API is only sending data in the JSON format. No HTML. No CSS. Just data. The serializer translates our Django models into JSON and then the client app translates JSON into a full-blown webpage. The reverse, deserialization, also occurs when our API accepts a user input–for example submitting a new todo–which is translated from HTML into JSON then converted into our Django model.

Inside our apis app we create a serializers.py and import our desired model by specifying which fields we want exposed.

      (todo) $ touch apis/serializers.py
# apis/serializers.py

from rest_framework import serializers
from todos import models


class TodoSerializer(serializers.ModelSerializer):
    class Meta:
        fields = (
            'id',
            'title',
            'description',
        )
        model = models.Todo

Next up is our view.DRF comes with several generic views that provides minimal functionality with a less code on our part.
We create a ListView and a DetailView of our todo items and specify the models and serializers for each view.

# apis/views.py

from rest_framework import generics

from todos import models
from .serializers import TodoSerializer

class ListTodo(generics.ListCreateAPIView):
    queryset = models.Todo.objects.all()
    serializer_class = TodoSerializer


class DetailTodo(generics.RetrieveUpdateDestroyAPIView):
    queryset = models.Todo.objects.all()
    serializer_class = TodoSerializer

All that's left is to update our API Urls both in the project level and app level.

# todo_project/urls.py

from django.contrib import admin
from django.urls import include, path


urlpatterns = [
    path('admin/', admin.site.urls),
    path('apis/v1/', include('apis.urls')),
]

The list of all todos will be at apis/v1/. Individual todo items will be at their pk which is automatically set by Django for us.


# apis/urls.py

from django.urls import path

from .views import ListTodo, DetailTodo

urlpatterns = [
    path('', ListTodo.as_view()),
    path('<int:pk>/', DetailTodo.as_view()),
]

We now have an API of our To do project.Start the local server.

    (todo) $ python manage.py runserver




Testing with the web browser

DRF comes with a very nice graphical user interface for our API.The listView for all items is at http://127.0.0.1:8000/apis/v1/.

https://wsvincent.com/assets/images/drf-todo/list.png

https://wsvincent.com/assets/images/drf-todo/detail.png

You can even use the forms on the bottom of each page to create, retrieve, destroy, and update new todo items.When your APIs become even more complex many developers like to use Postman to explore and test an API.

Voila,we have a working, albeit basic implementation of a Todo API.

For Part 1 of this blog. Thanks for the read.

Top comments (0)