Python is one of the top-rated programming languages. It’s also known for its less-complex syntax, and its high-level, object-oriented, robust, and general-purpose programming. Python is the top choice for any first-time programmer. Since its release in 1991, Python has evolved and powered by several frameworks for web application development, scientific and mathematical computing, and graphical user interfaces to the latest REST API frameworks.
This article is an excerpt taken from the book, ‘Hands-On RESTful API Design Patterns and Best Practices‘ written by Harihara Subramanian and Pethura Raj. This book covers design strategy, essential and advanced Restful API Patterns, Legacy Modernization to Microservices centric apps.
In this article, we’ll explore two comprehensive frameworks, Django and Flask, so that you can choose the best one for developing your RESTful API.
Django
Django is a web framework also available as open source with the BSD license, designed to help developers create their web app very quickly as it takes care of additional web-development needs. It includes several packages (also known as applications) to handle typical web-development tasks, such as authentication, content administration, scaffolding, templates, caching, and syndication. Let’s use the Django REST Framework (DRF) built with Python, and use it for REST API development and deployment.
Django Rest Framework
DRF is an open source, well-matured Python and Django library intended to help APP developers build sophisticated web APIs. DRF’s modular, flexible, and customizable architecture makes the development of both simple, turnkey API endpoints and complicated REST constructs possible. The goal of DRF is to divide a model, generalize the wire representation, such as JSON or XML, and customize a set of class-based views to satisfy the specific API endpoint using a serializer that describes the mapping between views and API endpoints.
Core features
Django has many distinct features including:
Web-browsable API
This feature enhances the REST API developed with DRF. It has a rich interface, and the web-browsable API supports multiple media types too. The browsable API does mean that the APIs we build will be self-describing and the API endpoints that we create as part of the REST services and return JSON or HTML representations. The interesting fact about the web-browsable API is that we can interact with it fully through the browser, and any endpoint that we interact with using a programmatic client will also be capable of responding with a browser-friendly view onto the web-browsable API.
Authentication
One of the main attractive features of Django is authentication; it supports broad categories of authentication schemes, from basic authentication, token authentication, session authentication, remote user authentication, to OAuth Authentication. It also supports custom authentication schemes if we wish to implement one. DRF runs the authentication scheme at the start of the view, that is, before any other code is allowed to proceed. DRF determines the privileges of the incoming request from the permission and throttling policies and then decides whether the incoming request can be allowed or disallowed with the matched credentials.
Serialization and deserialization
Serialization is the process of converting complex data, such as querysets and model instances, into native Python datatypes. Converting facilitates the rendering of native data types, such as JSON or XML. DRF supports serialization through serializers classes. The serializers of DRF are similar to Django’s Form and ModelForm classes. It provides a serializer class, which helps to control the output of responses. The DRF ModelSerializer classes provide a simple mechanism with which we can create serializers that deal with model instances and querysets. Serializers also do deserialization, that is, serializers allow parsed data that needs to be converted back into complex types. Also, deserialization happens only after validating the incoming data.
Other noteworthy features
Here are some other noteworthy features of the DRF:
- Routers: The DRF supports automatic URL routing to Django and provides a consistent and straightforward way to wire the view logic to a set of URLs
- Class-based views: A dominant pattern that enables the reusability of common functionalities
- Hyperlinking APIs: The DRF supports various styles (using primary keys, hyperlinking between entities, and so on) to represent the relationship between entities
- Generic views: Allows us to build API views that map to the database models
DRF has many other features such as caching, throttling, testing, etc.
Benefits of the DRF
Here are some of the benefits of the DRF:
- Web-browsable API
- Authentication policies
- Powerful serialization
- Extensive documentation and excellent community support
- Simple yet powerful
- Test coverage of source code
- Secure and scalable
- Customizable
Drawbacks of the DRF
Here are some facts that may disappoint some Python app developers who intend to use the DRF:
- Monolithic and components get deployed together
- Based on Django ORM
- Steep learning curve
- Slow response time
Flask
Flask is a microframework for Python developers based on Werkzeug (WSGI toolkit) and Jinja 2 (template engine). It comes under BSD licensing. Flask is very easy to set up and simple to use. Like other frameworks, it comes with several out-of-the-box capabilities, such as a built-in development server, debugger, unit test support, templating, secure cookies, and RESTful request dispatching. The powerful Flask RESTful API framework is discussed below.
Flask-RESTful
Flask-RESTful is an extension for Flask that provides additional support for building REST APIs. You will never be disappointed with the time it takes to develop an API. Flask-Restful is a lightweight abstraction that works with the existing ORM/libraries. Flask-RESTful encourages best practices with minimal setup.
Core features of Flask-RESTful
Flask-RESTful comes with several built-in features. Django and Flask have many common RESTful frameworks, because they have almost the same supporting core features. The unique RESTful features of Flask is mentioned below.
Resourceful routing
The design goal of Flask-RESTful is to provide resources built on top of Flask pluggable views. The pluggable views provide a simple way to access the HTTP methods. Consider the following example code:
class Todo(Resource): def get(self, user_id): .... def delete(self, user_id): .... def put(self, user_id): args = parser.parse_args() ....
Restful request parsing
Request parsing refers to an interface, modeled after the Python parser interface for command-line arguments, called argparser. The RESTful request parser is designed to provide uniform and straightforward access to any variable that comes within the (flask.request) request object.
Output fields
In most cases, app developers prefer to control rendering response data, and Flask-RESTful provides a mechanism where you can use ORM models or even custom classes as an object to render. Another interesting fact about this framework is that app developers don’t need to worry about exposing any internal data structures as its let one format and filter the response objects. So, when we look at the code, it’ll be evident which data would go for rendering and how it’ll be formatted.
Other noteworthy features
Here are some other noteworthy features of Flask-RESTful:
- API: This is the main entry point for the restful API, which we’ll initialize with the Flask application.
- ReqParse: This enables us to add and parse multiple arguments in the context of the single request.
- Input: A useful functionality, it parses the input string and returns true or false depending on the Input. If the input is from the JSON body, the type is already native Boolean and passed through without further parsing.
Benefits of the Flask framework
Here are some of the benefits of Flask framework:
- Built-in development server and debugger
- Out-of-the-box RESTful request dispatching
- Support for secure cookies
- Integrated unit-test support
- Lightweight
- Very minimal setup
- Faster (performance)
- Easy NoSQL integration
- Extensive documentation
Drawbacks of Flask
Here are some of Flask and Flask-RESTful’s disadvantages:
- Version management (managed by developers)
- No brownie points as it doesn’t have browsable APIs
- May incur a steep learning curve
Frameworks – a table of reference
The following table provides a quick reference of a few other prominent micro-frameworks, their features, and supported programming languages:
Language | Framework | Short description | Prominent features |
Java | Blade | Fast and elegant MVC framework for Java8 | Lightweight
High performance Based on the MVC pattern RESTful-style router interface Built-in security |
Java/Scala | Play Framework | High-velocity Reactive web
framework for Java and Scala |
Lightweight, stateless, and web-friendly architecture
Built on Akka Supports predictable and minimal resource-consumption for highly-scalable applications Developer-friendly |
Java | Ninja Web Framework | Full-stack web framework | Fast
Developer-friendly Rapid prototyping Plain vanilla Java, dependency injection, first-class IDE integration Simple and fast to test (mocked tests/integration tests) Excellent build and CI support Clean codebase – easy to extend |
Java | RESTEASY | JBoss-based implementation that integrates several frameworks to help to build RESTful Web and Java applications | Fast and reliable
Large community Enterprise-ready Security support |
Java | RESTLET | A lightweight and comprehensive framework based on Java, suitable for both server and client applications. | Lightweight
Large community Native REST support Connectors set |
JavaScript | Express.js | Minimal and flexible Node.js-based JavaScript framework for mobile and web applications | HTTP utility methods
Security updates Templating engine |
PHP | Laravel | An open source web-app builder based on PHP and the MVC architecture pattern | Intuitive interface
Blade template engine Eloquent ORM as default |
Elixir | Phoenix (Elixir) | Powered with the Elixir functional language, a reliable and faster micro-framework | MVC-based
High application performance Erlong virtual machine enables better use of resources |
Python | Pyramid | Python-based micro-framework | Lightweight
Function decorators Events and subscribers support Easy implementations and high productivity |
Summary
It’s evident that Python has two excellent frameworks. Depending on the choice of programming language you are intending to use and the required features, you can choose your type of framework to work on.
If you are interested in learning more about the design strategy, guidelines and best practices of Restful API Patterns, you can refer to our book ‘Hands-On RESTful API Design Patterns and Best Practices‘ here.
Read Next
Stack Overflow survey data further confirms Python’s popularity as it moves above Java in the most used programming language list.
Svelte 3 releases with reactivity through language instead of an API
Microsoft introduces Pyright, a static type checker for the Python language written in TypeScript