Debug School

rakesh kumar
rakesh kumar

Posted on

Difference between fastapi and flask and django

Feature and Application difference between fastapi and flask and django
Framework Type
Use Cases
Performance
Ease of Use
Flexibility
Learning Curve
Community and Ecosystem
Built-in Features
Asynchronous Support
ORM (Object-Relational Mapping)
Summary
Coding syntax difference between fastapi and flask and django

Setting Up a Basic Web Server
Routing with Path Parameters
Request Parsing
Handling Form Data
Response Objects
Middleware Implementation
Dependency Injection
Data Validation
Asynchronous Support
Database Integration
Template Rendering
Environment Configuration
Session Management
CSRF Protection
Authentication and Authorization
Static Files Serving
Background Tasks
Command Line Interface
Admin Interface

How to run Framework

Feature and Application difference between fastapi and flask and django

FastAPI, Flask, and Django are three popular web frameworks in Python, each with its own strengths and intended use cases. Here's a detailed comparison highlighting their key differences:

  1. Framework Type

FastAPI: A modern, high-performance web framework designed for building APIs quickly with Python 3.7+ based on standard Python type hints. It is asynchronous by default, making it well-suited for projects requiring high concurrency.

Flask: A microframework that provides the essentials needed to build web applications. It's lightweight and flexible, allowing developers to choose their own tools and libraries. Flask is synchronous by default, which is simple for most projects but may require additional libraries for handling async tasks.

Django: A full-stack web framework that comes with batteries included. It provides everything you need to build complex, data-driven websites, including an ORM, admin panel, authentication, and more. Django is synchronous, though it can support asynchronous operations with additional setup (e.g., Django Channels).

  1. Use Cases

FastAPI: Ideal for building APIs, especially those that need to handle high concurrency or require real-time features. It’s particularly suitable for modern applications that leverage async capabilities and need built-in validation and documentation.

Flask: Great for small to medium-sized web applications, REST APIs, and services where you need more control over your tools and libraries. Flask’s flexibility allows developers to add only what they need, making it suitable for microservices or single-page applications.

Django: Best for large, complex web applications where a lot of built-in functionality is beneficial. It’s suitable for projects where rapid development and a well-structured approach are needed, such as content management systems, e-commerce sites, and social networks.

  1. Performance

FastAPI: High performance, thanks to its async capabilities and use of Python type hints. It can outperform many other frameworks in terms of speed, making it a top choice for performance-critical applications.

Flask: Moderate performance, typically sufficient for most web applications. It’s synchronous, so handling a large number of concurrent connections may require additional tools like Celery or gevent.

Django: Moderate performance, optimized for developer productivity rather than raw speed. Like Flask, it’s synchronous, and additional tools (e.g., Django Channels) are needed for handling WebSockets or other async tasks.

  1. Ease of Use

FastAPI: Easy to use if you’re familiar with Python type hints and async/await. It automatically generates OpenAPI documentation, which can be a significant productivity boost.

Flask: Very easy to use and beginner-friendly. Its minimalistic approach allows developers to start quickly without much boilerplate.

Django: Steeper learning curve due to its comprehensive nature. However, once learned, it can significantly speed up development by providing out-of-the-box solutions for many common tasks.

  1. Flexibility

FastAPI: Moderately flexible, with a strong focus on API development. It’s less opinionated than Django but more structured than Flask.

Flask: Highly flexible, providing only the basics and letting developers choose their own libraries for everything else (e.g., database, authentication, etc.).

Django: Less flexible, as it enforces a specific way of doing things (e.g., use of its ORM, URL routing). This can be a benefit in terms of consistency and rapid development but may be limiting for some projects.

  1. Learning Curve

FastAPI: Moderate learning curve, especially if you’re familiar with modern Python features like async/await and type annotations. The automatic generation of API documentation makes it easier to understand.

Flask: Easy learning curve, especially for beginners. It’s straightforward and doesn’t impose much structure, making it easy to learn and use.

Django: Steeper learning curve due to its many built-in features and conventions. However, once mastered, it can significantly increase development speed and consistency.

  1. Community and Ecosystem

FastAPI: Growing rapidly, with increasing adoption and a strong focus on API development. The ecosystem is still maturing compared to Flask and Django.

Flask: Large and mature community with a vast ecosystem of extensions and libraries. There’s a lot of support and resources available for Flask developers.

Django: Very large and mature community with a rich ecosystem. Django has been around for a long time, and there’s a vast amount of documentation, plugins, and third-party packages available.

  1. Built-in Features

FastAPI: Focused on API features like automatic data validation, serialization, and documentation. It doesn’t include features like an ORM, but it integrates well with Pydantic and SQLAlchemy.

Flask: Minimalistic, with very few built-in features. Most additional functionality (like ORM or form handling) requires third-party extensions.

Django: Comes with many built-in features, including an ORM, authentication system, admin interface, form handling, and more. It’s designed to be a comprehensive framework that handles all aspects of web development.

  1. Asynchronous Support

FastAPI: Fully asynchronous, built from the ground up to support async/await. This makes it very efficient for I/O-bound tasks like handling multiple requests concurrently.

Flask: Synchronous by default, but can be made asynchronous with third-party libraries like gevent or asyncio.

Django: Synchronous by default, but supports async with Django Channels for WebSockets and other real-time features.

  1. ORM (Object-Relational Mapping)

FastAPI: No built-in ORM, but integrates well with third-party ORMs like SQLAlchemy or Tortoise-ORM.

Flask: No built-in ORM, but commonly used with SQLAlchemy via the Flask-SQLAlchemy extension.

Django: Comes with its own powerful ORM, tightly integrated with the rest of the framework. It’s a key part of Django’s approach to web development.

Summary:

FastAPI is best for building high-performance APIs with modern Python features, especially when you need async capabilities.
Flask is ideal for lightweight, flexible web applications where you want more control over your tools and architecture.
Django is perfect for large, complex web applications that benefit from a “batteries-included” approach, with many built-in features to speed up development.
Each of these frameworks excels in different scenarios, so the choice between them depends on the specific needs of your project.

Image description

Image description

Image description

Coding syntax difference between fastapi and flask and django

Setting Up a Basic Web Server

FastAPI:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"Hello": "World"}
Enter fullscreen mode Exit fullscreen mode

Flask:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello, World!"
Enter fullscreen mode Exit fullscreen mode

Django (using function-based views):

from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello, World!")
Enter fullscreen mode Exit fullscreen mode
  1. Routing with Path Parameters

FastAPI:

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
Enter fullscreen mode Exit fullscreen mode

Flask:

@app.route("/items/<int:item_id>")
def read_item(item_id):
    return {"item_id": item_id}
Enter fullscreen mode Exit fullscreen mode

Django:

from django.urls import path

urlpatterns = [
    path('items/<int:item_id>/', views.read_item),
]
Enter fullscreen mode Exit fullscreen mode
  1. Request Parsing

FastAPI:

from fastapi import Request

@app.post("/items/")
async def create_item(request: Request):
    data = await request.json()
    return {"data": data}
Enter fullscreen mode Exit fullscreen mode

Flask:

from flask import request

@app.route("/items/", methods=["POST"])
def create_item():
    data = request.json
    return {"data": data}
Enter fullscreen mode Exit fullscreen mode

Django:

from django.http import JsonResponse
import json

def create_item(request):
    data = json.loads(request.body)
    return JsonResponse({"data": data})
Enter fullscreen mode Exit fullscreen mode
  1. Handling Form Data

FastAPI:

from fastapi import Form

@app.post("/submit/")
async def submit_form(username: str = Form(...), password: str = Form(...)):
    return {"username": username}
Enter fullscreen mode Exit fullscreen mode

Flask:

@app.route("/submit/", methods=["POST"])
def submit_form():
    username = request.form['username']
    return {"username": username}
Enter fullscreen mode Exit fullscreen mode

Django:

from django.shortcuts import render

def submit_form(request):
    if request.method == 'POST':
        username = request.POST['username']
        return HttpResponse(username)
Enter fullscreen mode Exit fullscreen mode
  1. Response Objects

FastAPI:

from fastapi import Response

@app.get("/response/")
async def custom_response():
    return Response(content="Custom Response", media_type="text/plain")
Enter fullscreen mode Exit fullscreen mode

Flask:

from flask import Response

@app.route("/response/")
def custom_response():
    return Response("Custom Response", mimetype="text/plain")
Enter fullscreen mode Exit fullscreen mode

Django:

from django.http import HttpResponse

def custom_response(request):
    return HttpResponse("Custom Response", content_type="text/plain")
Enter fullscreen mode Exit fullscreen mode
  1. Middleware Implementation

FastAPI:

from fastapi import FastAPI
from starlette.middleware.base import BaseHTTPMiddleware

app = FastAPI()

class CustomMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        response = await call_next(request)
        response.headers["X-Custom-Header"] = "Value"
        return response

app.add_middleware(CustomMiddleware)
Enter fullscreen mode Exit fullscreen mode

Flask:

from flask import Flask, request

app = Flask(__name__)

@app.before_request
def before_request_func():
    print("Before request")

@app.after_request
def after_request_func(response):
    response.headers["X-Custom-Header"] = "Value"
    return response
Enter fullscreen mode Exit fullscreen mode

Django:

from django.utils.deprecation import MiddlewareMixin

class CustomMiddleware(MiddlewareMixin):
    def process_request(self, request):
        print("Before request")

    def process_response(self, request, response):
        response["X-Custom-Header"] = "Value"
        return response
Enter fullscreen mode Exit fullscreen mode
  1. Dependency Injection

FastAPI:

from fastapi import Depends

def get_query(query: str = None):
    return query

@app.get("/items/")
async def read_items(query: str = Depends(get_query)):
    return {"query": query}
Enter fullscreen mode Exit fullscreen mode

Flask:

Flask does not have built-in dependency injection like FastAPI.
Django:

Django does not have built-in dependency injection like FastAPI.

  1. Data Validation

FastAPI:

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: str = None

@app.post("/items/")
async def create_item(item: Item):
    return item
Enter fullscreen mode Exit fullscreen mode

Flask:

Flask does not have built-in data validation; you need to use additional libraries like Marshmallow.
Django:

from django import forms

class ItemForm(forms.Form):
    name = forms.CharField(max_length=100)
    description = forms.CharField(required=False)

def create_item(request):
    form = ItemForm(request.POST)
    if form.is_valid():
        return HttpResponse("Item valid")
Enter fullscreen mode Exit fullscreen mode
  1. Asynchronous Support

FastAPI:

@app.get("/async/")
async def async_endpoint():
    await some_async_function()
    return {"message": "This is async"}
Enter fullscreen mode Exit fullscreen mode

Flask:

Flask does not natively support async views (as of the latest stable version).

Django
Enter fullscreen mode Exit fullscreen mode

:

from django.http import JsonResponse
import asyncio

async def async_endpoint(request):
    await asyncio.sleep(1)
    return JsonResponse({"message": "This is async"})
Enter fullscreen mode Exit fullscreen mode
  1. Database Integration

FastAPI:

Usually combined with SQLAlchemy and databases libraries, with an async flavor:

from sqlalchemy.orm import Session

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.post("/items/")
async def create_item(db: Session = Depends(get_db)):
    db_item = ItemModel(name="name")
    db.add(db_item)
    db.commit()
Enter fullscreen mode Exit fullscreen mode

Flask:

Flask can use SQLAlchemy via Flask-SQLAlchemy:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy(app)

class Item(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))

@app.route('/items', methods=['POST'])
def create_item():
    item = Item(name="name")
    db.session.add(item)
    db.session.commit()
Enter fullscreen mode Exit fullscreen mode

Django:

Django comes with an ORM out of the box:

from myapp.models import Item

def create_item(request):
    item = Item.objects.create(name="name")
    return HttpResponse("Item created")
Enter fullscreen mode Exit fullscreen mode
  1. Template Rendering

FastAPI:

from fastapi.templating import Jinja2Templates

templates = Jinja2Templates(directory="templates")

@app.get("/render/")
async def render_template(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})
Enter fullscreen mode Exit fullscreen mode

Flask:

from flask import render_template

@app.route("/render/")
def render_template_view():
    return render_template("index.html")
Enter fullscreen mode Exit fullscreen mode

Django:

from django.shortcuts import render

def render_template_view(request):
    return render(request, "index.html")
Enter fullscreen mode Exit fullscreen mode
  1. Environment Configuration

FastAPI:

Environment variables are typically managed using external libraries like pydantic or dotenv.
Flask:

app.config['DEBUG'] = True
Enter fullscreen mode Exit fullscreen mode

Django:

Configuration is typically managed in the settings.py file:

DEBUG = True
Enter fullscreen mode Exit fullscreen mode
  1. Session Management

FastAPI:

Requires additional libraries like starlette.middleware.sessions:

from starlette.middleware.sessions import SessionMiddleware

app.add_middleware(SessionMiddleware, secret_key='some-secret-key')
Enter fullscreen mode Exit fullscreen mode

Flask:

from flask import session

app.secret_key = 'some-secret-key'

@app.route('/session/')
def session_view():
    session['key'] = 'value'
    return 'Session set'
Enter fullscreen mode Exit fullscreen mode

Django:

Sessions are configured by default in settings.py:

SESSION_ENGINE = "django.contrib.sessions.backends.db"

def session_view(request):
    request.session['key'] = 'value'
    return HttpResponse("Session set")
Enter fullscreen mode Exit fullscreen mode
  1. CSRF Protection

FastAPI:

Requires an external library like fastapi-csrf-protect.
Flask:

from flask_wtf.csrf import CSRFProtect

csrf = CSRFProtect(app)
Enter fullscreen mode Exit fullscreen mode

Django:

CSRF protection is enabled by default with middleware:

MIDDLEWARE = [
    'django.middleware.csrf.CsrfViewMiddleware',
    # other middleware
]
Enter fullscreen mode Exit fullscreen mode
  1. Authentication and Authorization

FastAPI:

from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/users/me")
async def read_users_me(token: str = Depends(oauth2_scheme)):
    return {"token": token}
Enter fullscreen mode Exit fullscreen mode

Flask:

Requires external libraries like Flask-Login:

from flask_login import LoginManager

login_manager = LoginManager()
login_manager.init_app(app)
Enter fullscreen mode Exit fullscreen mode

Django:

Comes with built-in authentication:

from django.contrib.auth.decorators import login_required

@login_required
def view(request):
    return HttpResponse("Authenticated")
Enter fullscreen mode Exit fullscreen mode
  1. Static Files Serving

FastAPI:

from fastapi.staticfiles import StaticFiles

app.mount("/static", StaticFiles(directory="static"), name="static")
Enter fullscreen mode Exit fullscreen mode

Flask:

Flask serves static files from 'static/' folder by default.
Django:

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
Enter fullscreen mode Exit fullscreen mode
  1. Error Handling

FastAPI:

from fastapi import HTTPException

@app.get("/error/")
async def raise_error():
    raise HTTPException(status_code=404, detail="Item not found")
Enter fullscreen mode Exit fullscreen mode

Flask:

from flask import abort

@app.route("/error/")
def raise_error():
    abort(404)
Enter fullscreen mode Exit fullscreen mode

Django:

from django.http import Http404

def raise_error(request):
    raise Http404("Item not found")
Enter fullscreen mode Exit fullscreen mode
  1. Background Tasks

FastAPI:

from fastapi import BackgroundTasks

def background_task(param: str):
    print(f"Task with {param}")

@app.post("/tasks/")
async def run_task(background_tasks: BackgroundTasks, param: str):
    background_tasks.add_task(background_task, param)
    return {"message": "Task added"}
Enter fullscreen mode Exit fullscreen mode

Flask:

Flask does not natively support background tasks; requires external tools like Celery.
Django:

from django.http import HttpResponse
from django_q.tasks import async_task

def run_task(request):
    async_task("myapp.tasks.background_task", "param")
    return HttpResponse("Task added")
Enter fullscreen mode Exit fullscreen mode
  1. Command Line Interface

FastAPI:

No built-in CLI; commonly used with tools like Typer or Click.
Flask:

from flask.cli import FlaskGroup

cli = FlaskGroup(app)
Enter fullscreen mode Exit fullscreen mode

Django:

Django has a built-in management CLI.
python manage.py runserver

  1. Admin Interface

FastAPI:

No built-in admin interface.
Flask:

Requires external libraries like Flask-Admin.
Django:

from django.contrib import admin

admin.site.register(ModelName)
Enter fullscreen mode Exit fullscreen mode

How to run Framework

FastAPI

Install Dependencies:
Ensure that you have FastAPI and a server like uvicorn installed:

pip install fastapi[all]
Enter fullscreen mode Exit fullscreen mode

Run the Project:
You typically run a FastAPI project using uvicorn:

uvicorn main:app --reload
Enter fullscreen mode Exit fullscreen mode

main is the name of the Python file (e.g., main.py).
app is the name of the FastAPI instance in that file (app = FastAPI()).
--reload is an optional flag that automatically reloads the server when you make changes to the code.

Flask

Install Flask:
Make sure Flask is installed:

pip install flask
Enter fullscreen mode Exit fullscreen mode

Set the Flask App Environment Variable:
You need to tell Flask which file to run. For example, if your main file is app.py:

On Windows:

set FLASK_APP=app.py
Enter fullscreen mode Exit fullscreen mode

On macOS/Linux:

export FLASK_APP=app.py
Enter fullscreen mode Exit fullscreen mode

Run the Flask App:
After setting the environment variable, you can run the Flask development server:

flask run
Enter fullscreen mode Exit fullscreen mode

To enable debug mode (automatic reloading on code changes), use:

flask run --debug
Enter fullscreen mode Exit fullscreen mode

Django

Install Django:
Install Django using pip:

pip install django
Enter fullscreen mode Exit fullscreen mode

Create a Django Project:
If you haven't created a project yet, you can do so with:

django-admin startproject myproject
Enter fullscreen mode Exit fullscreen mode

Replace myproject with your desired project name.

Run the Django Development Server:
Navigate to the project directory where manage.py is located and run:

python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

This starts the Django development server at http://127.0.0.1:8000/.
Run the Server on a Specific Port:
To run the server on a different port, specify it after the runserver command:

python manage.py runserver 8080
Enter fullscreen mode Exit fullscreen mode

This will run the server at http://127.0.0.1:8080/.

Top comments (0)