• Get In Touch
June 12, 2017

Django Rest Framework: A Guide

Need Hosting? Try ours, it's fast, reliable and feature loaded with support you can depend on.
View Plans

The Django Rest Framework, a django framework, is a toolkit used to build APIs (Application Program Interface) in Django models which is very powerful and flexible. An API is a collection of protocols, routines and tools used in building applications. Other known django frameworks include Tastypie and Piston.

DRF Requirements

The REST framework works well with the following versions of java python and django:

Python (2.7, 3.2, 3.3, 3.4, 3.5)
Django (1.8, 1.9, 1.10)

Why Django REST framework ?

A very easy to understand framework; Sometimes you might find yourself working with a framework that is most certainly limited or out of date, which ends up giving you a lot of issues. However, with DRF, you will be able to avoid all these issues due to:

  • Easy requirements, details and quick installation
  • Best scalable practices with API development
  • API guide for all the development work

While still on the course of developing your app, you might want to test the responses of JSON and your endpoints before the app is complete. DRF allows you to use the browsable API to see the results on the web, getting the response just the same way you would get it on the application.

A framework that is customizable and browsable; The source code of this framework is collected into components that allows one to simply import them into the project easily.

Some important components in DRF include:

Serializer classes; This allows the developer to model serialization from rest_framework import serializers from rest_framework import routers, serializers
Router Classes; This allows the developer to extend a class to be able to get pagination for their application. from rest_framework import routers, pagination, serializers

When we want to extend to other frameworks, the import statements that we would use would be:

from framework.apps.serializers import model_serializers, default_serializers
from framework.apps.routers import api_routers
from framework.apps.utils import pagination

When we simplify the structure of the framework, it means that we would find it easy to use the extensions of all the components and classes as well as the importation itself.

Adding DRF into your project

DRF setup

Installation:

The Django Rest Framewrok can be installed using two different methods:

The first method is by using pip. Open the terminal and run the following commands, one at a time:

pip install djangorestframework
pip install markdown      
pip install django-filter  

The second method is by cloning the project from github:

git clone git@github.com:tomchristie/django-rest-framework.git

After completing the steps above, you have now successfuly installed DRF. You will now need to add the rest framework. You can do this by adding rest_framework to the INSTALLED_APPS settings. You can do this by adding this line to the settings:

INSTALLED_APPS = (
    ...
    'rest_framework',
)

Most developers prefer using the API that is browsable. For one to be able to do that, you will have to add the login and logout views for the REST framework. You can do this by adding the following code to the urls.py file in the root folder:

urlpatterns = [
    ...
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

Note: It is important to note that the path of the URL can be anything that the developer wants, however, one must add the rest_framework.urls together with the rest_framework.

How DRF works

The REST framework consists of some building blocks that make it work properly. They include:

  • Class based views
  • Permissions and Authentication
  • Serialization
  • Viewsets and routers
  • Relationships and hyperlinked APIs
  • Responses and Requests
  • Client libraries and schemas

Class Based Views

This enables the developer to use class based views when writing the API views, instead of using views based on functions. One of the advantages of this is that it allows the developer to use most functionalities again and again, enabling them to have a dry code.

Permission and Authentication

This enables the developer to add restrictions to the API, which determine who can work on the code snippet. It gives restrictions on editing, deleting or updating the code. Some more functionalities of permissions and authentication include:

  • Restrictions on who can create snippets of code
  • All snippets belong to the creator alone, although can be shared by the creator
  • Read only access is granted to all unauthenticated requests
  • Updating and deleting permissions of a code snippet is only granted to the creator

Serialization

Instances of the snippet are serialized or deserialized to get representations such as those for xml and Json.

Using serialization, model instances and complex data are able to be converted to data types in native python language, enabling them to be easily rendered to other languages like XML and Python. It also allows deserialization, which is the back process of getting the date back to its original complex form.

Responses and Requests

The Django Rest Framework has a request object whose function is to extend the normal HttpRequest, providing a request parsing that is more flexible and easy to use. The request.data attribute is the major function of this object. We also have the request.data which works with arbitrary data.

Response objects are of the type TemplateResponse. Their work is to use content that has not been rendered, and then use negotiation of the content to get the right form of the content to be given to a client.

Relationships and hyperlinked API’s

A relationship in entities can be represented in different ways, these include:

  • Primary keys
  • Hyperlink in between entities
  • Use of a slug field on the entities
  • Using a string to represent the entities

All the above styles are supported by this framework, however, we would prefer the hyperlink method, which enables discoverability and cohesion of the API.

Viewsets and routers

Viewsets are used to allow the developer pay more attention on developing the interactions and states of the API, making the URL construction and automatic affair of the framework. The ViewSet class provides more features including update, read, put and get which are not available in the view classes.

Schemas and Client Libraries

A schema is a document that is machine readable, and is used to give a description of all the API endpoints available with their URLs and their supported operations. Schemas are very important when working with documentation that is automatically generated.

Conclusion

This tutorial has taken you through introduction, installation and building blocks of a Django Rest Framework. Having understood this, you are on your way to been a good and competent developer in DRF.

Need Hosting? Try ours, it's fast, reliable and feature loaded with support you can depend on.
View Plans

Share this Article!

Related Posts

Node.js Authentication – A Complete Guide with Passport and JWT

Node.js Authentication – A Complete Guide with Passport and JWT

Truth be told, it’s difficult for a web application that doesn’t have some kind of identification, even if you don’t see it as a security measure in and of itself. The Internet is a kind of lawless land, and even on free services like Google’s, authentication ensures that abuses will be avoided or at least […]

Node.js and MongoDB: How to Connect MongoDB With Node

Node.js and MongoDB: How to Connect MongoDB With Node

MongoDB is a document-oriented NoSQL database, which was born in 2007 in California as a service to be used within a larger project, but which soon became an independent and open-source product. It stores documents in JSON, a format based on JavaScript and simpler than XML, but still with good expressiveness. It is the dominant […]

Using MySQL with Node.js: A Complete Tutorial

Using MySQL with Node.js: A Complete Tutorial

Although data persistence is almost always a fundamental element of applications, Node.js has no native integration with databases. Everything is delegated to third-party libraries to be included manually, in addition to the standard APIs. Although MongoDB and other non-relational databases are the most common choice with Node because if you need to scale an application, […]

Node.Js Vs Django: Which Is the Best for Your Project

Node.Js Vs Django: Which Is the Best for Your Project

Django and NodeJs are two powerful technologies for web development, both have great functionality, versatile applications, and a great user interface. Both are open source and can be used for free. But which one fits your project best? NodeJs is based on JavaScript, while Django is written in Python. These are two equally popular technologies […]

Nodejs Vs PHP:  Which Works Best?

Nodejs Vs PHP: Which Works Best?

Before getting into the “battle” between Node.js and PHP we need to understand why the issue is still ongoing. It all started with the increased demand for smartphone applications, their success forcing developers to adapt to new back-end technologies that could handle a multitude of simultaneous requests. JavaScript has always been identified as a client-side […]