Django Rest Framework Example


Django Rest Framework Example Author: Mohammad Amaan Abbasi | Aug. 4, 2018

Learn the basics of Django rest framework. In the tutorial, you will learn how to serialize python models to json objects. Hence, creating a simple Rest api.

For the purpose of this tutorial, We will serialize a Post model, in a posts app.

But before that, let's understand what REST is.

REST in a Nutshell

Representational State Transfer (REST) is an architectural style for structuring web API. It means, interacting with an API over HTTP - making requests to specific URLs, to get relevant data in the response.

In HTTP, we have methods like GET,POST, DELETE and PUT e.t.c . GET and POST are the most common.

GET is used to get information from the server, and POST to create new objects.

Installing Django RestFramework

Let's start by installing DjangoRestframework:

pip install djangorestframework

And,

INSTALLED_APPS = [
    ...,
    'posts',
    'rest_framework',
]

Like, I told you before that I will be using a posts app. So before we proceed, let's look at the models first.

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=120)
    content = models.TextField()

if you have any confusion you can check the full code here.

Creating the serializer

Create a serializer.py file in the app (posts) directory. This will have the serializer class that will convert the python models to json format.

Import serializers and the model class. Here, I have used the ModelSerializer class, It help us in many ways. Firstly, based on our models it will generate the set of fields for us. Secondly, it will generate validators for the serializer. Thirdly, It includes simple default implementations of .create() and .update().

In short, it prevents us from writing redundant code.

Writing the views using our serializer

In views.py file:

PostView is inherting from ModelViewSet which provides a layer of abstraction. We only need to provide a queryset and the serializer_class ,and we are good to go.

Now, we are left with configuring the urls.

Configuring urls

djangorestframework provide us with routers. By using routers, we no longer need to deal with wiring up the URL conf ourselves. They are automatically generated.

We have build our REst API, now let's test it.

go to localhost:8000.

django REst framework


To create a new post:

localhost:8000/posts.

django REst framework


django REst framework


django REst framework


To check whether the REst API is working as intended, login to admin account and check for the post.

Summary

We learnt about what REst is, and some of its common methods GET and POST. We used Django rest framework to built a REst api that converts the python models to json objects.