A Guide On Building RESTful API’s Using Python Frameworks

A Guide On Building RESTful API’s Using Python Frameworks

What is a RESTful API?

A RESTful API, also known as a RESTful web service, is based on REpresentational State Transfer (REST), an architecture and an approach towards communications often used for developing web services.

RESTful APIs are rapidly growing in popularity. The integration and development of application architecture is subtly but quickly changing, and the world has arrived at a juncture where APIs are not a privilege anymore, but a necessity.

What’s the Driving Force behind the Popularity of RESTful APIs?

The following factors have contributed to making RESTful APIs grow more popular over time.

In the past:

2006: API pioneers eBay, Amazon and Google Maps were among the first to offer popular Web APIs.
2007: The mobile revolution was kicked off by smart phones.
2013: Mobile and infotainment platform diversity (Jolla, BB10, Tizen, Ubuntu, WP, FF OS, Android etc).

In the future:

2015+: Babylonic language diversity (Rust, Go, Dart).
2016+: Internet of things (vehicles, household appliances, power sockets and much more).
15B connected devices in 2015, 40B connected devices in 2020.

Given that RESTful APIs are going to become a more integral part of the future, in this article we explain how to build them by utilising some common Python Frameworks.

Understanding REST Constraints

REST constraints are design rules that are applied to establish the distinct characteristics of the REST architectural style.

The formal REST constraints are:

  • Client-Server
  • Stateless
  • Cache
  • Interface / Uniform Contract
  • Layered System
  • Code-On-Demand

Each constraint is a pre-determined design decision that can have a both positive and negative impact. The intent is for the positives of each constraint to balance out the negatives to produce a stable architecture that resembles the Web.

The Django REST Framework

Setup is very easy for REST integration in Django

Sample settings.py file needed to get started with REST Framework

INSTALLED_APPS = (
   'rest_framework',
)

REST_FRAMEWORK = {
   'DEFAULT_AUTHENTICATION_CLASSES': (
       'need_done.lib.authentication.CsrfExemptSessionAuthentication',
   ),
   'DEFAULT_PERMISSION_CLASSES': (
       'rest_framework.permissions.IsAuthenticated',),
   'EXCEPTION_HANDLER': 'need_done.lib.exceptions.custom_exception_handler',
}

Let’s take a look at a quick example of using Rest Framework to build a simple model-backed API.

A common Read/Write API for accessing information of the users of a project.

from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets

# Serializers define the API representation.

class UserSerializer(serializers.HyperlinkedModelSerializer):
   class Meta:
       model = User
       fields = ('url', 'username', 'email', 'is_staff')

# ViewSets define the view behavior.

class UserViewSet(viewsets.ModelViewSet):
   queryset = User.objects.all()
   serializer_class = UserSerializer

# Routers provide an easy way of automatically determining the URL conf.

router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.

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

The REST framework is fully customizable from defining permissions to authenticating. You can provide your own exception handling. It integrates easily with both sql and nosql databases.

A Few More Useful RESTful Frameworks

Flask

A microframework for Python based on Werkzeug, Jinja 2 and Good Intentions.

Pros of using the Flask microframework

  • Lightweight
  • Minimal
  • Open source
  • Well documented
  • Easy to use
  • Well designed
  • Easy to install

Cons of using the Flask microframework:
– No support for form processing(writing form in HTML, validating the data on an ad-hoc basis, writing the SQL to write to the database)

Django REST Framework:

A powerful and flexible toolkit for building Web APIs.

Pros of using the Django REST Framework

  • Web browsable API is a huge usability win for your developers
  • Authentication policies including packages for OAuth1a and OAuth2
  • Serialization that supports both ORM and non-ORM data sources
  • Customizable all the way down – just use regular function-based views if you don’t need the more powerful features
  • Extensive documentation, and great community support
  • Used and trusted by internationally recognised companies including Mozilla, Red Hat, Heroku, and Eventbrite
  • It’s easy to use, customizable, pluggable, and provides immaculate serialization of data
  • Follows idiomatic django. If you are comfortable with class-based views, forms and so on, you’ll feel right at home with this framework
  • Provides out of the box REST functionality using ModelViewSets. At the same time, provides greater control for customization using CustomSerializer, APIView, GenericViews etc
  • Better authentication. Easier to write custom permission classes. Works great with third party libraries and OAuth. On that note, you may want to include DJANGO-REST-AUTH for social authentication/registration purposes

Cons of using the Django REST Framework

  • If you don’t know Django very well, don’t go for this
  • Magic! Can be difficult to understand.  Magic has been written on top of Django’s class based views which are in turn quite complex in nature
  • Has a steep learning curve

Tastypie REST Framework:
Pros of using the Tastypie REST Framework:

  • Easy to get started with and provides basic functionalities out of the box
  • Most of the time you won’t be dealing with Advanced Django concepts like class based views, Forms etc
  • More readable code and less of magic!
  • If your models are NON-ORM, go for it

Cons of using the Tastypie REST Framework:

  • Doesn’t strictly follow idiomatic Django (Keep in mind that Python and Django’s philosophies are quite different)
  • As your app or site grows, it may be a bit more difficult to customize APIs
  • No support for O-Auth.

These different REST frameworks should give you an idea of which are best for your specific needs. Try them out and choose the one that you’re most comfortable with that matches your project specifications. If you need a quick consultation, don’t hesitate to connect with our team here.

Vaidehi Bhargava

April 5, 2017

Comments

  1. Excellent information, but there are several complements to be observed in relation to Flask.

    Plugging Flask into SQLAlchemy / Flask-SQLAlchemy for models and the Marshmallow (Flask-Marshmallow / Marshmallow-SQLAlchemy) library, to handle serialization and data validation, it becomes a highly flexible and powerful alternative.

Leave a Reply

Your email address will not be published. Required fields are marked *