Skip to content
Man watching his own design

Common Pitfalls of Building RESTful APIs In Django For Your Front-end Framework - Read Time: 10 Mins

  • Django
  • Python

📅 June 24, 2018

⏱️7 min read

"It's not about your resources, it's about your resourcefulness" By Tony Robbins

Introduction

For more than 3 months there's always been a nagging question on my mind, Which was  "How do i integrate Django and a frontend framework like React, Vue or Angular?" 

The answer only came to me when i was watching a Youtube tutorial that talks about having both Django and React playing nice.

In the end the answer to my question was actually quite simple. Which was to build Django REST API endpoints to service frontend frameworks.

Which lead me to explore on using a Django package extensively over the last couple of months called Django Rest Framework to accomplish this task

What is RESTful API?

REST API is called Representational State Transfer (REST). Essentially it's a online resource provided by a software developer or organisation. Who exposes it on their server for you to build useful applications.

Their purpose is to allow you to do a very specific task by interacting the API using your own web browser without lifting a finger. 

Think checking when's the movie times for the latest movie, checking of today's weather, searching for your favourite songs on Spotify or just ordering a Pizza.

There's endless amount of these APIs floating online for you to use.

Installation List

First off to build REST API on Django, you need to pip install the following to make it work for you.

Some of these packages requires further configurations to make it work for your own specific purpose. I had added it into the Links sections for you to configure those packages. 

Especially the CORS headers package that needs to be configured before any of your front-end frameworks like Angular or React could consume your REST API. 

pip install djangorestframework

pip install markdown 

pip install django-filter 

pip install django-cors-headers

pip install drf-nested-routers

pip install requests

Django Rest Framework Breakdown

Django Rest API Breadown

The Django REST API endpoint is broken down into 3 separate parts namely Serializer, Viewset and Router.

To store data or make changes to the database, it interacts with a instance of the database table from Django models which is called "models.py"

Serializer

The purpose of serializer is to allow database queries to be converted  or unconverted into Python based data types.

Where the serializer job is to display data in a certain  format that is JSON or XML other types display content.

Do note that you have to create your own Django model first, before proceeding in creating a serializer for your own endpoint.

The code below shows the Django model called Account  is being used to create a serializer that is AccountSerializer.

serializer.py

from rest_framework import serializers
from .models import Account

class AccountSerializer(serializers.ModelSerializer):
  class Meta():
    model=Account
    fields=('id','account_name','users','created')

Viewsets

Viewsets are ways for the user to initiate operations to manipulate data that resides in the database through HTTP requests of a Rest API URL using a browser.

Take for a example  creating a new record or updating existing records in the database, these are some operations that you could use for HTTP requests.

Database Operations and HTTP requests

Generic views are viewsets with pre-built templates, that covers general uses of a typical REST API endpoint. Besides that the sample code  below is used for building a viewset.

Generic Views:

CreateAPIView - provides a POST request to create a new record in the database

ListAPIView - GET request that retrieves a list of records found in the database that is non-editable by the user.

RetrieveAPIView - A GET request which only retrieves a single database record that is non-editable by the user.

UpdateAPIVIew - Issues a PUT request to the database which updates a existing record.

DestroyAPIView - Destroys a single record found in the database by issuing a DELETE request

view.py

from django.contrib.auth.models import User
from myapp.serializers import UserSerializers
from rest_framework generics
from rest_frameworks.permissions import IsAdminUser

class UserList(generics.ListAPIView):
  queryset = User.objects.all()
  serializer_class = Userserializer
  permission_classes = (IsAdminUSer)

Router

It's purpose is make your life easy by handling all the various combination of requests and URLs.

The routes does it by grouping various viewsets you had created under a single endpoint.

Which greatly reduces you the need to specify the their own individual URLs

routers.py

from rest_frameworks import routers
from .views import UserViewSet, AccountViewSet

routers = routers.DefaultRouter()
router.register(r'users'UserViewSet)
routerregister(r'accounts'AccountViewSet)

urls.py

from .routers import router
urlpatterns = [
  url(r^forgot-password/$, ForgotPasswordFormView.as_view()),
  url(r^api/, include((router.url, 'app_name'),
  namespace='instance_name'))
  )
]

Consuming Existing REST API

Despite the near limitless amount of REST API endpoints, there's a need for you to know. That when your using endpoints provided by external providers.

There might be lack of updated documentations, speed issues and last but not least the need to pay for API services.  

It could range from monthly subscriptions or paid per certain amount of requests to support the API  service providers. 

Luckily most API service providers that i know of has trial periods.  Which limits a certain amount of requests that could be used by you.

Therefore it might be a great ideal to optimise the amount of requests that you might use from external API providers when your developing your own API endpoints.

CORS Header

CORS is called Cross Origin Request Sharing it's purpose is to check, if the web browser has the correct permissions in order to access the endpoint.

Do note that when your using any front end web framework or technology be it React, Vue or Angular.

You have to install the django-cors-header package and configure it under the django's settings to allow front-end frameworks to access to the Django's endpoints. 

Conclusion

Building endpoints in Django that works with your front-end is not a easy task.

Especially in terms of designing the functionality of each endpoints has not been covered.

I had added a links to the article on design decisions that you have to take note in building REST API endpoints for your front-end.

Which has proved to be very helpful for me in designing REST APIs for my work in the past few months.

Lastly i had included tutorial videos that teaches you on how to build REST API endpoints from scratch 

React & Django Tutorial Integration //REACTify Django

https://youtu.be/AHhQRHE8IR8

Django Rest Framework Quickstart

http://www.django-rest-framework.org/tutorial/quickstart/

How To Use RESTful APIs With Django

https://simpleisbetterthancomplex.com/tutorial/2018/02/03/how-to-use-restful-apis-with-django.html

Build a REST API with The Django REST Framework

https://youtu.be/tG6O8YF91HE

Write an API for Almost Everything (Introduction to Rest Framework)

https://youtu.be/lzgCHgLA-2U

10 Best Practices for Better RESTful API

https://blog.mwaysolutions.com/2014/06/05/10-best-practices-for-better-restful-api/

Cross Origin Resources Sharing

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Django CORS Headers

https://github.com/ottoyiu/django-cors-headers





← PrevNext →
  • Powered by Contentful
  • Max Ong Zong Bao's DEV Profile