Hot Posts

6/recent/ticker-posts

Top 15 Python REST API Frameworks in 2022

 

Python web frameworks

Python has emerged as one of the most popular programming languages over the last two decades. Part of the reason for this is its focus on readability and the ease of learning. Over the years, Python has found acceptance in many niche domains, such as automation & utility programs. However, most importantly, it has found enormous favor in the data analytics and scientific programming community.

In addition to this, Python has also evolved with the web. From the early days of Web1.0 to the advancements in Web2.0 that also features the REST architecture for defining API, a lot of Python-based web development frameworks have sprung up.

In this blog post, we look at the current state of the art in terms of Python-based REST API frameworks as we cover the most robust and popular Python REST API frameworks.

Capabilities of REST API Frameworks

A framework provides a collection of tools and libraries to aid programmers in completing a task. For instance, the framework offers libraries that make it easier to code the web front end, the web back end, or both if the goal is to construct a web application.

In this instance, the framework supplies boilerplate code to make the programming logic simpler while abstracting away the difficulties of carrying out the various web application tasks individually. A pattern of software development is defined by some advanced frameworks, which additionally specify their syntax and semantic principles for building the program in a particular way.

Depending on the complexity and the capabilities, the framework can be a single library, a bunch of libraries, or a set of libraries, configuration files, and tools such as compilers, transpilers, and other programs.

When it comes to building REST APIs, frameworks can provide various facilities to streamline the application development processes across the client and server-side sub-systems of the application. Since REST APIs are just like Web APIs, most frameworks are targeted for building web applications, consisting of Web APIs. Typically a web framework consists of many different components.

The function of each component can be described as follows:

Client

  1. UI: This component defines the user interface layer of the framework, responsible for rendering the client application, typically on a web browser.
  2. Access Control: This component is responsible for managing authentication and authorization of users for accessing the application.
  3. Application: This is the core component that manages application-related functions such as templates, navigation, exceptions, and logging.
  4. HTTP: This component handles the sending of HTTP requests and parsing of responses.

Server

  1. App Middleware: This is the application code that handles the server-side business logic for the web application. Usually, this component is responsible for generating the dynamic HTML snippets to be sent to the client for UI rendering based on a template or the MVC (Model View Controller) pattern. It also handles application data formatting and exception handling.
  2. Data: This component acts as an abstraction layer for storing/retrieving data from databases or data stores.
  3. Access Control: This component is responsible for managing authentication and authorization of users for accessing the server-side resources.
  4. Misc/Utilities: These are a bunch of utility libraries and tools for supporting additional features. These features mainly include session handling, caching, logging, internationalization, localization, and error handling. Additionally, some frameworks also allow provision for including pluggable modules in the web application.
  5. Security: This component is responsible for protocol-level security measures. It includes the support for HTTP related security measures such as SSL, HTTPS, CORS. It may also include advanced security measures such as rate-limiting or specific features for application-level security.
  6. HTTP: This component handles the incoming HTTP requests and mapping them to appropriate routes for application business logic execution. Additionally, it may handle response formatting and support for custom HTTP headers.

If a web framework includes all the components, then it is a full-stack web framework.

For web frameworks built on Python, there are certain omissions. Since Python is not used in browsers, its role in building frontend web applications is nil. However, Python is still used for building desktop and command-line applications, which may communicate with an existing REST API backend.

Therefore in the case of Python, the overall scope of the web framework is more server heavy. At the client-side, Python’s scope is limited to providing HTTP libraries for making API calls to the server.

However, if the intention is to build a REST API backend, fewer components are needed at the server end.

For REST APIs, App middleware is not relevant, as REST APIs do not generate application-specific HTML views.

Additionally, some components, such as Data and Misc/Utilities, are optional. The full-stack frameworks usually have them. Nevertheless, there are micro frameworks that do not provide these components and give developers the option to integrate with third-party libraries.

As an example, a Python-based REST API micro-framework may not provide the data component. In that case, the developer can use the SQLAlchemy toolkit, a popular Python-based database library, to build a custom data component for accessing the database.

Note: The definition of micro frameworks is a bit fuzzy. While most micro frameworks have an opinionated design approach towards one component, some of them do offer all the components with a reduced set of features or capabilities compared to full-stack frameworks.

Choosing the Right REST API Framework

So you have decided to use Python in your next software project. However, the project is designed around the REST API architecture. If you are in a dilemma on which REST API framework to choose for building the application, then we have got you covered.

The choice of REST API Framework boils down to three key considerations:

  1. Role: The role played by the framework. Strictly speaking, for web applications, the role can be either client or server. The same applies to REST APIs. Either you are using the framework for invoking a REST API from the client-side or deploying a REST API interface at the server-side.
  2. Scope: This refers to the components you are looking for in the application. If your REST API interface is part of a full-fledged web application, then its better to use a full-stack web framework that lets you build the web application backend together with the REST API interface. Otherwise, for building the REST API interface alone, you can choose a micro-framework that provides the essential functions required to build the base for REST APIs.
  3. Scale: The scale refers to the ability of the framework to handle a specific load. In software, this is fundamentally defined by the required computing power and memory consumption. The most apparent indicator of scale for web-based applications is the amount of concurrent client-server interactions that the server can handle.

The handling of scale is outside the scope of the framework components. This issue mostly concerns the infrastructure and the deployment strategy of the application server. However, in the interest of keeping things in control, you should choose a lightweight and fast framework such that it does not consume too many server resources and does not block the client requests for too long.

Above all, the choice of the REST API framework for any project is also governed by time. If you want to build something quick as a proof of concept, then you would choose a micro framework. However, if you are planning for a production-grade application, you would want to take some time to choose the right full stack framework and ramp-up to learn to use it.

Moreover, if you only wish to build a client-side Python application that is intended to consume an existing REST API service, all you need is a REST API client library.

Let us peek into the various Python REST API frameworks that are in active development and have a decent adoption in 2020. We have categorized these frameworks into client libraries, microframeworks, and a full-stack framework for your convenience.

TL;DR: If you want to get a quick comparative analysis of all the frameworks covered here, take a look at the comparison table at the end of this post.

Best Python API Frameworks

Requests

Category: Client Library

The Requests library is a very popular HTTP client library in Python. The official Python documentation also recommends it. As the name suggests, this library is used to make API requests, and it supports all the HTTP methods and advanced HTTP features such as authentication, session cookies, SSL handling, and more.

You can check out the requests GitHub repository or access the quickstart guide.

Invoking an HTTP GET API using requests is as simple as this.

import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))

#Get the HTTP Response Code
r.status_code

#Get HTTP Response Body
r.text

Faster Than Requests

Category: Client Library

This library mimics the Requests library. However, as the name suggests, it is faster than the Requests library. You can check the README file to check the performance and claims made by the developer of this library. It also claims to be lightweight, in terms of the lines of code.

The best part about this library is a bunch of utility functions beyond the usual HTTP methods. This library provides some convenient utility functions for tasks such as scraping URLs, downloading resources such as image files, or clubbing requests to multiple URLs and returning a single response.

You can take a closer look at the GitHub repository, and try out the example code. Here is how you can initiate a bunch of API requests from this library to fetch a URL, download an image, and scrape a few URLs in different ways.

import nimporter
import faster_than_requests as requests

requests.get("http://httpbin.org/get") # GET
requests.post("http://httpbin.org/post", "Some Data Here") # POST
requests.download("http://example.com/foo.jpg", "out.jpg") # Download a file
requests.scraper(["http://foo.io", "http://bar.io"], threads=True) # Multi-Threaded Web Scraper
requests.scraper5(["http://foo.io"], sqlite_file_path="database.db") # URL-to-SQLite Web Scraper
requests.scraper6(["http://python.org"], ["(www|http:|https:)+[^s]+[w]"]) # Regex-powered Web Scraper

PycURL

Category: Client Library

PycURL is a Python wrapper over the libcurl library for multiprotocol file transfer. It supports HTTP, FTP, SMTP, and many other Internet protocols. If you are a fan of the cURL or libcurl library, you will be able to relate to this Pythonic interface over the native C/C++ based libcurl.

To get a closer look, explore the GitHub repository of PycURL. Here is a glimpse of how you can make an HTTP GET call using PycURL.

import pycurl
from io import BytesIO

buffer = BytesIO()
c = pycurl.Curl()
c.setopt(c.URL, 'http://pycurl.io/')
c.setopt(c.WRITEDATA, buffer)
c.perform()
c.close()

body = buffer.getvalue()
# Body is a byte string.
# We have to know the encoding in order to print it to a text file
# such as standard output.
print(body.decode('iso-8859-1'))

Flask

Category: Micro Framework

Flask is a massively popular web framework for Python. With over 50k stars on GitHub, it is the most widely used and well-adapted framework for building web applications using Python.

Over the years, Flask has added a lot of feature updates, which makes it almost as good as a full stack framework. However, a minimalistic approach to building web applications is what makes it a preferred choice for developers. Here is how you can write a simple “Hello World” web application in Flask.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
return 'Hello, World!'

Tornado

Category: Micro Framework

Tornado is a Python web framework and asynchronous networking library. It also bundles an HTTP server and client interface along with a WebSocket interface for bi-directional communication with WebSocket enabled servers.

The Tornado web framework has the essential middleware features required for handling HTTP requests/responses, templating, and routing. It also supports co-routines that makes it ideal for building long polling and persistent connection based web backends, especially for WebSockets.

Tornado has been around for a long time, but some of its features are a bit dated compared to modern REST frameworks. However, it enjoys much love on the GitHub repo with over 19k stars.

To get started with a simple Tornado web application, you can define a simple API backend like this.

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")

def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])

if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()

FastAPI

Category: Micro Framework

FastAPI is one of the upcoming Python web frameworks. It claims to be very fast, highly performant and supports a compact coding structure that results in super-fast development.

FastAPI is based on the asyncio capabilities of Python, which has been standardized as ASGI specification for building asynchronous web applications. In terms of features, FastAPI is almost at par with Flask and supports inbuilt capabilities for integrating with databases, running background tasks, plugging in custom application middleware, and more.

With over 14k stars, FastAPI is gaining much popularity in the Python community and is under active development with over 100 contributors.

Here is how you define a simple REST API backend with the FastAPI framework.

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def read_root():
return {"Hello": "World"}


@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}

Sanic

Category: Micro Framework

Sanic is yet another asyncio based Python web framework. It is a lightweight framework with support for all the essential HTTP and app middleware functionalities. However, it does not have in-built support for the data component.

Additionally, Sanic supports the ability to write custom protocols and middleware components for customizing the protocol request and response handling. It has an inbuilt development web server but integrates well with Nginx for production applications.

Here is how to write a simple API backend server in Sanic.

from sanic import Sanic
from sanic.response import json

app = Sanic()

@app.route('/')
async def test(request):
return json({'hello': 'world'})

if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)

Falcon

Category: Micro Framework

Falcon aims to be a reliable web framework for building large scale app backends and microservices. It encourages the REST architectural style and works with WSGI or ASGI compatible servers.

Falcon has an object-oriented, class-based interface for defining API resources. It supports the essential HTTP and app middleware features, including HTTP protocol handling, routing, media handling, cookies, and URI utilities.

This is how you define a REST API resource using the Falcon’s object-oriented approach.

class QuoteResource:

def on_get(self, req, resp):
"""Handles GET requests"""
quote = {
'quote': (
"I've always been more interested in "
"the future than in the past."
),
'author': 'Grace Hopper'
}

resp.media = quote


api = falcon.API()
api.add_route('/quote', QuoteResource())

Bottle

Category: Micro Framework

Bottle is a very lightweight micro framework. It has a small footprint and is distributed as a single file and depends only on the Python standard library.

Bottle provides all the essential middleware components for building a REST API backend that relies on routing and templates. It supports most of the usual HTTP related features such as cookies, headers, metadata, and file uploads. It has a built-in HTTP server too.

A quick and simple Bottle web application looks like this.

from bottle import route, run, template

@route('/hello/<name>')
def index(name):
return template('<b>Hello {{name}}</b>!', name=name)

run(host='localhost', port=8080)

For more details, take a look at the Bottle GitHub repository, or head over to the tutorials.

Hug

Category: Micro Framework

Hug is truly a multi-interface API framework. It offers an excellent way to build REST APIs by separating the API business logic from the interface and associating version dependencies.

Because of its focus on building APIs, Hug is strictly limited to input/output handling, routing, and type annotations. However, it supports provision for adding extensions. One of Hug’s cool features is its ability to expose an API logic via CLI, HTTP, or a local function, thus offering multiple interfaces.

Here is how you define an API in Hug.

import hug

@hug.get(examples='name=Timothy&age=26')
@hug.local()
def happy_birthday(name: hug.types.text, age: hug.types.number, hug_timer=3):
"""Says happy birthday to a user"""
return {'message': 'Happy {0} Birthday {1}!'.format(age, name),'took': float(hug_timer)}

Eve

Category: Micro Framework

Eve is an API micro framework built on top of Flask.

Eve’s goal is to make REST API development extremely fast and simple. Because of this, it builds upon the Flask principles, leaving aside all the web application components of Flask.

Eve supports the most used REST API interface patterns such as CRUD operations, customizable API endpoints, filtering, sorting, pagination, JSON/XML/JSONP formats.

It also supports advanced features such as authentication, CORS, caching, rate limiting, and more. Eve also has support for integrating with MongoDB and SQL databases.

Eve provides a Python configuration setting file to define the API resources and endpoints. In this way, the REST APIs can be built using a declarative JSON syntax.

For more details, take a look at the Eve quickstart guide, or browse the GitHub repository.

Django

Category: Full Stack Framework

Django is a full-featured, full stack web framework in Python. It is one of the oldest and the most popular web frameworks, with nearly 50k stars on GitHub.

The Django framework is loaded with many features for building fully capable web applications. Beyond the essential HTTP and application middleware, its capabilities include MVC pattern and data views, database handling, forms, templates, security, caching, and much more.

If you are only interested in building a REST API backend, Django is an overkill. However, you can use the Django REST framework, which is a community funded project by Encode. It uses Django as the underlying engine by providing a more straightforward interface that is specific to REST API development.

You can check out the code repository of Django and Django REST framework for more details.

TurboGears

Category: Full Stack Framework

TurboGears is a full stack web framework. However, it is designed to scale from a single file application to a full stack application. In this way, TurboGears gives the developers a feel of a micro framework yet providing powerful tools to scale up to host a full-fledged web application.

TurboGears is built on the MVC pattern, just like the other full stack frameworks. It supports, templating, pagination, authentication, and authorization, caching, along with support for few databases and schema migration.

Explore the TurboGears GitHub repository to get a closer look at the framework. To get a headstart on development, check out the TurgoGears documentation.

web2py

Category: Full Stack Framework

Web2py is a Python-based web framework focussing on database-driven web applications.

At the core, web2py has the modules for handling HTTP and URLs. It also has a built-in scheduler for running background tasks. Additionally, web2py has a database abstraction layer that maps Python objects into database objects, such as tables, queries, and records. The database abstraction layer works in conjunction with a set of drivers supporting many of the popular databases such as SQLite, MySQL, PostgreSQL, Oracle, DB2, MSSQL, MongoDB, and more.

It also has a full-featured MVC support, form validation, security, access control, and many more utilities.

You can read more about it in the web2py online book. For a closer look, you can browse the web2py GitHub repository.

Pyramid

Category: Full Stack Framework

Pyramid is yet another full stack Python web framework that believes in starting small and growing big. This approach allows the developers to start with Pyramid as a micro framework. Further, Pyramid is flexible enough to expand and add more components to take care of all aspects required for building a large scale web application.

Pyramid framework includes all the standard features of a web framework such as MVC pattern, routing, templating, security, session, databases, and logging. It includes a web server called pserve, but it works well with Apache and Nginx for production deployment.

Here is how you create a simple web backend with Pyramid.

from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response

def hello_world(request):
return Response('Hello World!')

if __name__ == '__main__':
with Configurator() as config:
config.add_route('hello', '/')
config.add_view(hello_world, route_name='hello')
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 6543, app)
server.serve_forever()

Related Blog Posts

Want to Learn More?

→ Click Here to Launch Your Online Business with JasperAI