In this lesson we want to talk about Top 10 Best Python REST API Frameworks, Python is popular and nice programming language, Python is used for web development and different tasks. there are many frameworks available in Python to support web development, including Flask, Django, Pyramid, Tornado, CherryPy, Bottle, Flask-RESTfu and etc. These frameworks provides developers with different tools and resources to create robust and scalable web applications quickly and easily. also Python has large and active Python community offers many libraries, plugins and tools to help developers with their web development projects. and in this article we will completely talk about Top 10 Best Python REST API Frameworks.
What is REST API ?
REST (Representational State Transfer) API is software architectural style that defines set of constraints to be used for creating web services. It is web based API and is based on HTTP protocol. RESTful APIs use HTTP requests to POST (create), PUT (update), GET (read) and DELETE (delete) data. RESTful API can be used by a number of clients like mobile devices, desktop applications and websites. It is a lightweight and flexible alternative to traditional Web Services and is often used to build modern and scalable applications.
Top 10 Best Python REST API Frameworks
These are top 10 best Python REST API frameworks:
What is Flask ?
Flask is lightweight Python web framework that provides useful tools and features for creating web applications. it is easy to get started, and also provides simple and easy way to create dynamic web pages using Python. Flask is based on Werkzeug WSGI library and Jinja2 template engine, and it offers flexible way to handle request and response objects, route URLs to views and handle database connection. it is good for small to medium sized web applications, and it can also be easily extended with different plugins and extensions.
How to Install Flask?
You can install Flask using pip, open your terminal or command and run following command in your terminal:
1 |
pip install Flask |
This is simple REST API example using Flask:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
from flask import Flask, jsonify, request app = Flask(__name__) # create a list of dictionaries to represent books books = [ { 'id': 1, 'title': 'Book 1', 'author': 'Author 1' }, { 'id': 2, 'title': 'Book 2', 'author': 'Author 2' }, { 'id': 3, 'title': 'Book 3', 'author': 'Author 3' } ] # route to handle GET requests to retrieve all books @app.route('/books', methods=['GET']) def get_books(): return jsonify({'books': books}) # route to handle GET requests to retrieve a single book @app.route('/books/<int:book_id>', methods=['GET']) def get_book(book_id): book = [book for book in books if book['id'] == book_id] if len(book) == 0: return jsonify({'message': 'Book not found'}), 404 return jsonify({'book': book[0]}) # route to handle POST requests to add a new book @app.route('/books', methods=['POST']) def add_book(): book = { 'id': books[-1]['id'] + 1, 'title': request.json['title'], 'author': request.json['author'] } books.append(book) return jsonify({'book': book}), 201 if __name__ == '__main__': app.run(debug=True) |
This code defines simple REST API with three routes to retrieve all books, retrieve single book, and add new book. books are stored in list of dictionaries and the Flask jsonify function is used to convert the books to JSON format and return them in the response.
What is Django REST Framework ?
Django REST framework (DRF) is third party library for Django, and it used for building, testing and debugging RESTful APIs written using the Django framework. django rest framework provides complete and well documented tools, and it will help you to build and test APIs. it has features like request parsing, request and response handling and serialization. DRF also provides support for authentication and permissions and it makes it easy to build secure and robust APIs.
How to Install Django REST Framework (DRF)?
First of all install Django REST framework by running the following command in your terminal:
1 |
pip install djangorestframework |
Now let’s create a simple DRF project, after installation, add ‘rest_framework’ to your INSTALLED_APPS list in your Django settings file. Then, include the following in your urls.py file:
1 2 3 4 5 6 7 8 9 10 |
from django.urls import path, include from rest_framework import routers from .views import BookViewSet router = routers.DefaultRouter() router.register(r'books', BookViewSet) urlpatterns = [ path('', include(router.urls)), ] |
In your views.py file, create a ViewSet class to handle the CRUD operations for books:
1 2 3 4 5 6 7 |
from rest_framework import viewsets from .models import Book from .serializers import BookSerializer class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer |
Create models.py file to define the Book model:
1 2 3 4 5 6 7 8 |
from django.db import models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) def __str__(self): return self.title |
Finally create serializers.py file to define the serializers for the Book model:
1 2 3 4 5 6 7 |
from rest_framework import serializers from .models import Book class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('id', 'title', 'author') |
Now you can run your Django server and access the REST API endpoints at http://localhost:8000/books/. you can use provided CRUD operations to interact with the books in the database.
What is FastAPI?
FastAPI is modern and high performance web framework for building APIs with Python 3.7+ based on standard Python type hints. it is built on top of Starlette for the web parts and Pydantic for the data parts.
FastAPI has number of advantages compared to other Python web frameworks, including
Fast to code: decrease the amount of redundant code, increase productivity. -Fewer bugs: reduce about 40% of human (developer) induced errors.
Easy to maintain: FastAPI makes it easier to keep the code up to date.
Fast to run: FastAPI is very high performance on par with NodeJS and Go (thanks to Pydantic and async support). one of the fastest Python frameworks available.
FastAPI also integrates with other popular libraries such as Django ORM, Tortoise ORM and asyncio.
How to Install FastAPI?
You can install FastAPI by using pip with the following command in your terminal or command prompt:
1 |
pip install fastapi |
This is basic example of a REST API using FastAPI:
1 2 3 4 5 6 7 8 9 10 11 |
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} |
In this example we have defined two endpoints: one at the root URL (“/”) and one at “/items/{item_id}”. read_root function returns simple JSON response {“Hello”: “World”}.
For runing the code, you can open a terminal window in the same directory as the code file and run the following command:
1 |
uvicorn main:app --reload |
In here, main is the name of the file containing the code and app is the instance of the FastAPI application. –reload flag ensures that the server automatically reloads when changes are made to the code.
What is Tornado ?
Tornado is an open source Python based web framework and asynchronous network library. it is designed to handle large amounts of traffic and long lived connections, and it is a good choice for real time web applications such as chat applications, online games and online real time data services. Tornado includes web server and supports WebSockets and other asynchronous features which allows for efficient and high performance handling of many simultaneous connections.
How to Install Tornado ?
For installing Tornado you can use Python pip. Run the following command in your terminal:
1 |
pip install tornado |
This is simple example of Tornado REST API:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import tornado.ioloop import tornado.web import json import datetime class CurrentDatetimeHandler(tornado.web.RequestHandler): def get(self): now = datetime.datetime.now() response_dict = { 'date': now.strftime("%Y-%m-%d"), 'time': now.strftime("%H:%M:%S") } self.write(response_dict) def make_app(): return tornado.web.Application([ (r"/", CurrentDatetimeHandler), ]) if __name__ == "__main__": app = make_app() app.listen(8080) tornado.ioloop.IOLoop.current().start() |
In this example Tornado Application is created with single handler, CurrentDatetimeHandler which returns the current date and time in JSON format in response to GET request. The application listens on port 8080 and starts the Tornado IOLoop to handle incoming requests.
What is Pyramid?
Pyramid is an open source web framework. and it is designed to be highly configurable and flexible and it is good choice for both small and large web applications. Pyramid follows the Model View Template (MVT) pattern and provides features such as URL routing, template engine integration and database abstraction layer. It is also easy to extend with plugins and packages and it allows developers to add new functionality as needed. Pyramid is known for its simplicity and ease of use and it is popular choice for beginners and experienced Python developers.
How to Install Pyramid?
For installing Pyramid you can use pip. Run the following command in your terminal:
1 |
pip install pyramid |
This is basic example of a REST API built with Pyramid that returns the current date and time:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
from pyramid.config import Configurator from pyramid.response import Response import json import datetime def get_current_datetime(request): now = datetime.datetime.now() response_dict = { 'date': now.strftime("%Y-%m-%d"), 'time': now.strftime("%H:%M:%S") } return Response( body=json.dumps(response_dict), content_type='application/json; charset=UTF-8' ) def main(global_config, **settings): config = Configurator(settings=settings) config.add_route('datetime', '/') config.add_view(get_current_datetime, route_name='datetime') return config.make_wsgi_app() if __name__ == '__main__': from wsgiref.simple_server import make_server server = make_server('0.0.0.0', 8080, main({})) server.serve_forever() |
You can run this code by saving it to a file like app.py and running python app.py in your terminal or command prompt. You can then access the date and time information by making a GET request to http://localhost:8080 in your web browser or using a tool like curl. The response will be in JSON format, containing the current date and time.
What is Bottle?
Bottle is minimalist, single file, fast and lightweight Python web framework for building small to medium sized web applications. it is designed to be easy to use and it provides simple and expressive API for creating HTTP based web services. Bottle does not require any external dependencies or separate server and can be run as standalone web application. Bottle supports different features such as URL routing, request handling and template engine integration and it is choice for building small to medium sized web applications. despite its simplicity, Bottle is also highly extensible and developers can add custom functionality by using plugins and middleware.
How to Install Bottle?
For installing bottle you can use pip. Run the following command in your terminal :
1 |
pip install bottle |
This is basic example of a REST API built with Bottle that returns the current date and time:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
from bottle import Bottle, response, run import json import datetime app = Bottle() @app.route('/') def get_current_datetime(): now = datetime.datetime.now() response_dict = { 'date': now.strftime("%Y-%m-%d"), 'time': now.strftime("%H:%M:%S") } response.content_type = 'application/json' return json.dumps(response_dict) run(app, host='0.0.0.0', port=8080) |
You can run this code by saving it to a file like app.py and running python app.py in your terminal or command prompt. You can then access the date and time information by making a GET request to http://localhost:8080 in your web browser or using a tool like curl. The response will be in JSON format, and it contains the current date and time.
What is CherryPy?
CherryPy is an open source Python web framework for building web applications. It is designed to be simple to use, fast and scalable and also provides clean and elegant API for building HTTP based services. CherryPy allows developers to build web applications using Python and focuses on easy of use and performance. it provides full featured and stand alone HTTP server, and can also be integrated with popular web servers such as Apache and Nginx. CherryPy supports many features such as request handling, URL routing and template engine integration and provides plug in system that allows developers to extend its functionality. it is good choice for building scalable and performant web applications in Python.
How to Install CherryPy?
For installing CherryPy, you can use Python pip. Run the following command in your terminal:
1 |
pip install cherrypy |
This is simple example of REST API built with CherryPy that returns the current date and time:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import cherrypy import json import datetime class DateTimeAPI: @cherrypy.expose def index(self): now = datetime.datetime.now() response = { 'date': now.strftime("%Y-%m-%d"), 'time': now.strftime("%H:%M:%S") } return json.dumps(response) cherrypy.config.update({'server.socket_host': '0.0.0.0'}) cherrypy.config.update({'server.socket_port': 8080}) cherrypy.quickstart(DateTimeAPI()) |
You can run this code by saving it to a file like app.py and run python app.py in your terminal or command prompt. You can then access the date and time information by making a GET request to http://localhost:8080 in your web browser or using a tool like curl. The response will be in JSON format, and it contains the current date and time.
What is Flask-RESTful ?
Flask-RESTful is an extension for Flask, It is a micro web framework in Python, You can use that for building RESTful APIs. it provides simple and easy way to define resources and routes, also handles request parsing, response generation and error handling.
with Flask-RESTful, you can define resource as Python class with methods that correspond to HTTP methods like GET, POST, etc. resource class can be registered with the API using the api.add_resource method. this allows you to easily build and define the behavior of your REST API, with added benefits of using the Flask framework for your application.
How to Insall Flask-RESTful?
To install Flask-RESTful you can use pip:
1 |
pip install flask-restful |
This is basic example of using Flask-RESTful to create REST API:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
from flask import Flask from flask_restful import Api, Resource, reqparse import datetime app = Flask(__name__) api = Api(app) class CurrentDatetime(Resource): def get(self): now = datetime.datetime.now() response_dict = { 'date': now.strftime("%Y-%m-%d"), 'time': now.strftime("%H:%M:%S") } return response_dict api.add_resource(CurrentDatetime, '/') if __name__ == '__main__': app.run(debug=True) |
In this example Flask application is created with the Flask class. The Api class is instantiated with the Flask application, creating an instance of a RESTful API. resource class, CurrentDatetime is defined that returns the current date and time in a dictionary in response to GET request. resource class is then added to the API using the api.add_resource method. Finally, the Flask application is run with debug mode enabled.
What is Connexion?
Connexion is Python library for building and documenting RESTful APIs, built on top of the Flask web framework. it allows you to define your API using OpenAPI widely used specification for REST APIs and provides automatic validation of incoming requests and responses based on the defined OpenAPI specification.
How to Install Connexion?
For installing Connexion you can use pip package manager:
1 |
pip install connexion |
This is basic example of a REST API built using Connexion:
1 2 3 4 5 6 7 8 9 10 11 12 |
from connexion import FlaskApp, App from connexion.resolver import RestyResolver app = FlaskApp(__name__, specification_dir='.') app.add_api('api.yml', resolver=RestyResolver('api')) @app.route('/') def hello(): return {"message": "Hello, World!"} if __name__ == '__main__': app.run(port=8080) |
In this example first of all we have imported the required classes from the connexion module. after that we have created FlaskApp instance and add our API definition from a YAML file named api.yml to it. Next we define simple endpoint for the root path (/) that returns a JSON response with message. finally we run the application on port 8080.
Note that in this example OpenAPI specification for the API is stored in the file api.yml, which Connexion will use to automatically generate the required code to handle incoming requests and generate responses.
What is Hug?
Hug is Python library for building RESTful APIs. It is a fast and minimalistic framework for creating APIs with focus on speed and simplicity. Hug allows developers to quickly create RESTful APIs by simply declaring the API functions and decorating them with Hug specific annotations, without the need for complex routing definitions.
How to Install Hug?
You can install Hug using pip. for installing the latest version of Hug simply run the following command in terminal:
1 |
pip install hug |
This is simple example of how to create a RESTful API using Hug:
1 2 3 4 5 6 7 8 |
import hug @hug.get("/greet") def greet(name: hug.types.text): return {"message": "Hello {0}".format(name)} if __name__ == '__main__': hug.API(__name__).http.serve(port=8000) |
This will start the API server on port 8000, which you can access using a web browser or a tool like curl by sending a GET request to http://localhost:8000/greet?name=John.
Which Top 10 Frameworks is Best for Python REST API ?
The best framework for your REST API will depend on your particular requirements, such as the complexity of the API, the performance requirements, the team’s experience with a particular framework, etc.
Subscribe and Get Free Video Courses & Articles in your Email