REST – Representational State Transfer
This defines a set of architectural guidelines that are used for the design and development of the World Wide Web.
REST API: The API which is developed using REST is known as REST API/ RESTful API.
The client makes HTTP requests to an API. The API will communicate to the web application/database (if needed). The web application/database provides required data to the API. Further, the API returns response data to the client.
GET: A simple get request such as a request to a particular web page.
POST: Send a post request or send data to the server.
PUT: It takes the given URI and searches for a record in the URI. If it exists, it updates the record, or else creates a new record.
DELETE: Deletes a particular record at the given URI.
PATCH: Updates the individual fields of a record.
(2xx) Success – 200 Success 201 Created 202 Accepted
(3xx) Redirections
(4xx) Client Error- 404 Not Found
(5xx) Server Error- 500 Internal Server Error.
Basically, this starts with a base URI (for example http://abc.com/api) to actually point to different data
Must have HTTP methods (such as GET, POST, PUT, PATCH and DELETE)
Is stateless, like HTTP
Includes media type to define state transition data elements (JSON)
RESTful APIs have endpoints (Ex: http://abc.com/api/user/1. We can service the endpoint using HTTP methods such as GET to retrieve user 1 data and DELETE to delete user 1 and so on).
DRF is a library that works on top of Django. It is a powerful toolkit for developing web APIs that has great support for serialization.
You can install DRF using Python’s package manager, i.e., a pip command.
1 2
pip install django pip install djangorestframework
django-admin startapp firstapp
Next, open the settings.py file of your project and add ‘rest framework’ to INSTALLED_APPS. Also, add the name of the app we just created (firstapp).
1 2 3 4 5 6 7 8 9 10
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', ‘firstapp’, ]
Next, we create a simple model class. Here, I will be creating a simple book model as shown below:
1
2
3
4
5
6
7
8
9
10
11
from django.db
import models
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length = 250)
description = models.TextField()
def __str__(self):
return self.title
Run the below commands to create a table (for migrations).
1
2
Python manage.py migrate
Python manage.py makemigrations
Next, we create a superuser using the command
1
2
3
4
5
6
python manage.py createsuperuser
Username(leave blank to use 'admin'): abc
Email address: abc @gmail.com
Password: ** **
Password(again):
Superuser created successfully.
Then, we check if it’s working.
Python manage.py runserver
Go to localhost/admin/ and log in to your account. As of now, you will not find any table over here.
To do so, we need to go to admins.py file and register our model as below:
1
2
3
4
5
6
7
8
from django.contrib
import admin
from.models
import Book
# Register your models here.
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ["id", "title", "description"]
Let us now refresh the page:
Since we have not added any book details, click and add a few books (two or three).
To convert complex data types such as query sets and model instances to native Python data types we use serializers. These native Python data types can then be easily rendered into JSON, XML, or other content types. Serializers convert Python objects or model instances to JSON (or XML).
Serializers package (when data is going to the server) and unpackage (when data is coming from the server) data.
Different types of serializers in Django Rest Framework:
Serializer: Transforms normal Python objects to JSON; we should create all the fields ourselves.
ModelSerializer: Transforms model query set to JSON and vice versa, fields are generated based on the model fields, CRUD operations on the model.
HyperLinkedSerializer: Uses hyperlinks to represent relationships, rather than primary keys, including a URL field instead of a primary key field.
ListSerializer: Serializing and validating multiple objects at once. You won’t typically need to use it directly, customize the create or update behavior of multiple bulk objects.
BaseSerializer: This is useful if you want to implement new generic serializer classes similar to the serializer class, change serialization and deserialization styles, customize serialization or deserialization behavior, or add new behavior for new serializer base classes.
If you are familiar with Django forms, you will see that a serializer class is similar to that.
Creating a Serializer Class:
It is best practice to create a separate serializers.py file to write all serializers. You need to import serializers from rest_framework as shown in the below example.
Example:
1
2
3
4
5
6
from rest_framework
import serializers
class BookSerializer(serializers.Serializer):
title = serializers.CharFiels(max_length = 100)
description = serializers.TextField()
ModelSerializer: Transforms model query set to JSON and vice versa, fields are generated based on the model fields, CRUD operations on the model.
Let us now create our model serializer class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#
import serializer from rest_framework
from rest_framework
import serializers
#
import model from models.py
from.models
import Book
# Create a model serializer
class BookSerializer(serializers.ModelSerializer):
# specify model and fields
class Meta:
model = Book
fields = ('title', 'description')
Writing Views:
There are two types of views - function-based views and class-based views.
We use the @api_view decorator (includes GET and POST requests) when we are working with function-based views.
We use APIView class when we are working with class-based views.
In my API, I am using ModelViewSet. The ModelViewSet class inherits from the GenericAPIViews class.
Viewsets combine the logic for a set of related views in a single class. Please note that the viewsets do not provide any method handlers such as .get() or .post(). Instead they provide actions such as .list(), .create() ,etc.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from django.shortcuts
import render
# Create your views here.
#
import viewsets
from rest_framework
import viewsets
#
import local data
from.serializers
import BookSerializer
from.models
import Book
# create a viewset
class BookViewSet(viewsets.ModelViewSet):
# define queryset
queryset = Book.objects.all()
# specify serializer to be used
serializer_class = BookSerializer
Setting Up URLs:
Insert the below code in the urls.py folder inside the project folder.
1 2 3 4 5 6 7 8 9 10
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), #add firstapp urls path('', include("firstapp.urls")) ]
Create an urls.py file inside the app folder and add the below code.
Here, we will be calling our viewset. To do so we use routers.REST framework which adds support for automatic URL routing to Django. There are two types of routers - simple router and default router. In this example, I am using a DefaultRouter. We import routers from rest_framework and then we create an object of the class DefaultRouter and finally register our viewset.
After doing so we add the path to router.urls to URL patterns as shown in the below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# basic URL Configurations from django.urls import include path # import routers from rest_framework import routers from.views import * #import everything from views # define the router router = routers.DefaultRouter() # define the router path and viewset to be used router.register(r 'Book', BookViewSet) # specify URL Path for rest_framework urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls')) ]
Finally, we go ahead and test our API using the command below.
python manage.py runserver
Let us add a new book using the post option. You will get a success message with “ HTTP 201 Created”.
The final list of books we have added.
Thanks for reading about a basic API using Django Rest Framework. In this API, we created a single model and used ModelSerializer. Further, we created views using viewsets, and finally, we have set up our URLs using routers.
However, it is impossible to cover all the concepts in detail in a single article. There is a lot more to be learned about DRF. One of the advantages of DRF is that it has good community support and documentation. Refer to the documentation at https://www.django-rest-framework.org/tutorial/quickstart/ to learn more and have fun building interesting APIs. For community support refer to https://www.django-rest-framework.org/community/tutorials-and-resources/.