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
Postmodel, in a
But before that, let's understand what REST is.
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.
Let's start by installing DjangoRestframework:
pip install djangorestframework
INSTALLED_APPS = [ ..., 'posts', 'rest_framework', ]
Like, I told you before that I will be using a
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.
serializer.py file in the app (
posts) directory. This will have the serializer class that will convert the python models to json format.
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
In short, it prevents us from writing redundant code.
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.
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.
To create a new post:
To check whether the REst API is working as intended, login to admin account and check for the post.
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.