Square CloudSquare Cloud

FastAPI, Flask or Django: which to choose for your API

It depends on the size and kind of project. FastAPI fits new APIs with validation and docs generated from type hints, Flask fits small, flexible services, and Django with DRF fits systems that want an ORM, admin and authentication built in.

Updated 8 min read

Learning objectives

After reading this article you will be able to:

  • Compare FastAPI, Flask and Django on async, validation, ORM and project size
  • See the same endpoint written in all three frameworks
  • Know which production server each one uses and which to pick for your scenario
On this page

FastAPI, Flask and Django are the three most cited Python web frameworks, but they start from different ideas. Flask is a small core you complete with extensions. Django is the opposite: it ships an ORM, migrations, authentication and an admin interface out of the box. FastAPI was built for APIs and uses Python type hints to validate input and generate documentation.

To compare them, the three examples below implement the same endpoint: POST /tasks, which requires a non-empty title field, answers 201 with the created task and an error when the input is invalid. This guide is about the choice. The step-by-step for deploying each one is in how to host FastAPI, Flask or Django.

Which criteria matter?#

  1. Async and concurrency. If the API spends a lot of time waiting on other APIs, WebSockets or streaming, an ASGI framework with async def end to end handles more connections per process. If it runs quick, synchronous database queries, WSGI with a few workers is enough.
  2. Validation. Whether input is validated from a declaration (types, schema, serializer) or with hand-written if checks.
  3. ORM, admin and authentication included. How much of what every app needs (tables, migrations, users, a screen to edit data) ships with the framework.
  4. Project and team size. A 50-line webhook and a system with dozens of tables and several developers need different things.
  5. API documentation. Whether the framework generates an OpenAPI schema and an interactive page with no extra work.

The database is a separate choice, covered in the best database for Python; connecting through psycopg or SQLAlchemy is in how to connect PostgreSQL to Python.

When should you choose FastAPI?#

FastAPI declares the request body as a Pydantic model. From that declaration, it reads the JSON, converts types, validates and hands the ready object to your function. The same models feed the OpenAPI schema, served with an interactive page at /docs (Swagger UI) and another at /redoc.

pip install "fastapi[standard]", file main.py:

python
from uuid import uuid4

from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class TaskIn(BaseModel):
    title: str = Field(min_length=1)


@app.post("/tasks", status_code=201)
def create_task(task: TaskIn):
    return {"id": str(uuid4()), "title": task.title}

To try it, fastapi dev main.py. Invalid input gets a 422, with a detail JSON pointing at the field and the problem. The function is a plain def on purpose: FastAPI runs sync functions in a threadpool so they don't block the server. Use async def when the libraries you call support await, and def when they block, like many database drivers; the docs themselves recommend def when in doubt.

Pros: validation, conversion and docs from type hints; native async on ASGI; editor autocompletion across the whole flow; simple dependency injection for authentication and connections.

Cons: no ORM, migrations or admin (you pick SQLAlchemy, SQLModel or another, plus Alembic for migrations); mixing async def with a blocking library stalls the whole process, a common beginner mistake.

When should you choose Flask?#

Flask is a small core: routing, request, response and templates. Everything else (database, validation, login, CORS) comes from extensions. That keeps code short and explicit, good for small services and for anyone who wants to understand every piece.

pip install flask, file app.py:

python
from uuid import uuid4

from flask import Flask, request

app = Flask(__name__)


@app.post("/tasks")
def create_task():
    data = request.get_json(silent=True)
    title = data.get("title") if isinstance(data, dict) else None
    if not isinstance(title, str) or not title:
        return {"error": "title is required"}, 400
    return {"id": str(uuid4()), "title": title}, 201

To try it, flask --app app run --debug. get_json(silent=True) returns None when the body isn't JSON, and validation is hand-written. A bigger project would add a validation library, such as Pydantic itself or marshmallow.

Flask accepts async def views with the flask[async] extra, but it is still a WSGI application. Its docs are direct: each request still ties up one worker, even for async views, and Flask's async support is less performant than async-first frameworks. For a mainly async codebase, the docs themselves suggest Quart, a reimplementation of Flask on ASGI.

Pros: little to learn; explicit code, no magic; a large ecosystem of extensions; good for webhooks, prototypes and microservices.

Cons: no built-in validation, ORM or OpenAPI docs; as the project grows, its structure depends on the team's discipline; async limited by the WSGI model.

When should you choose Django with Django REST Framework?#

Django describes the database in Python classes (the ORM), generates migrations with makemigrations and automatically builds an admin interface to edit data, with one registration line per model. Authentication, sessions and CSRF protection come ready. For APIs, the usual route is Django REST Framework (DRF), which adds serializers, authentication, permissions and a browsable API.

bash
pip install django djangorestframework
django-admin startproject mysite .
python manage.py startapp tasks

Add "rest_framework" to INSTALLED_APPS in mysite/settings.py. In tasks/views.py:

python
from uuid import uuid4

from rest_framework import serializers, status
from rest_framework.decorators import api_view
from rest_framework.response import Response


class TaskSerializer(serializers.Serializer):
    title = serializers.CharField(max_length=200)


@api_view(["POST"])
def create_task(request):
    serializer = TaskSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    return Response(
        {"id": str(uuid4()), **serializer.validated_data},
        status=status.HTTP_201_CREATED,
    )

And in mysite/urls.py:

python
from django.contrib import admin
from django.urls import path

from tasks.views import create_task

urlpatterns = [
    path("admin/", admin.site.urls),
    path("tasks", create_task),
]

To try it, python manage.py runserver. CharField rejects blank text by default, and raise_exception=True turns a failure into a 400 response with errors per field. The example saves nothing so it stays comparable to the other two. In a real project, the task would be a model: with a ModelSerializer and a ModelViewSet registered on a router, DRF generates list, create, retrieve, update and delete, and the Django admin can edit the tasks.

Pros: ORM, migrations, admin and authentication included; a standard structure anyone who knows Django recognizes; DRF covers permissions, pagination and serialization; a mature ecosystem.

Cons: more moving parts for a small API; async exists but is partial: Django supports async views under ASGI and most of the ORM has async variants, but, according to the docs, transactions don't work in async mode; for OpenAPI, DRF's docs recommend third-party packages such as drf-spectacular.

Which production server does each one use?#

Framework Interface Production server Typical command
FastAPI ASGI Uvicorn (included in fastapi[standard]) fastapi run main.py or uvicorn main:app --host 0.0.0.0
Flask WSGI Gunicorn gunicorn -b 0.0.0.0:8000 'app:app'
Django WSGI (or ASGI) Gunicorn (or Uvicorn, under ASGI) gunicorn mysite.wsgi -b 0.0.0.0:8000

The built-in servers (fastapi dev, flask run, runserver) are for development and listen on 127.0.0.1 by default, which leaves outside traffic unanswered (see EADDRINUSE and 502 after the deploy). In production, each Gunicorn or Uvicorn worker is a process with its own copy of the app in memory, so more workers means more RAM. The full commands, Django's ALLOWED_HOSTS settings and the most common errors are in how to host FastAPI, Flask or Django.

How do the three compare side by side?#

Criterion FastAPI Flask Django + DRF
Interface ASGI WSGI WSGI or ASGI
Async native async views, but one worker per request async views; most of the ORM; no async transactions
Validation Pydantic, from type hints manual or via extension DRF serializers
ORM and migrations separate (SQLAlchemy, Alembic) separate (extensions) built in
Admin no no built in
OpenAPI docs automatic at /docs via extension via extra package
Sweet spot small to large API small service medium to large system

Which one should you choose for each scenario?#

Scenario Recommendation
New JSON-only API, with validation and docs FastAPI
Backend for an AI app that calls other APIs FastAPI, with async def
Webhook, prototype or small microservice Flask
System with many tables, users and staff who edit data Django with DRF
Site with HTML pages and an API in the same project Django
Existing Flask or Django project that works Keep it; switching rarely pays for the migration

If you're torn between FastAPI and Django, ask how much of the app is CRUD over tables with an admin screen. If it's almost all of it, Django saves weeks. If the API is more integration than data entry, FastAPI carries less weight. Before opening it to the public, go through the API production checklist.

How to do this on Square Cloud#

An API in FastAPI, Flask or Django uses the Square Cloud Python runtime. You upload the project as a ZIP in the dashboard, or deploy with the CLI, GitHub or the VS Code extension, and on start the platform runs pip install -r requirements.txt, so the production server (Uvicorn or Gunicorn) goes in that file. The squarecloud.app file is optional: the dashboard generates it at deploy time.

The start command holds the production server from the table above, listening on 0.0.0.0 on the port from the PORT variable, which the platform sets. An example to adapt: uvicorn main:app --host 0.0.0.0 --port $PORT. There is no build step, and the start command runs as a shell command: with Django, migrate and collectstatic can run before Gunicorn, chained with &&.

For the Django ORM or SQLAlchemy, PostgreSQL and MySQL hosting starts on the Standard plan (from R$44.99 per month), in the same datacenter as your apps. You copy the connection URL from the dashboard into an environment variable, and the connection requires TLS, with the certificate the dashboard provides.

Each worker takes memory, and a web app uses at least 512 MB of the plan's RAM; Hobby starts at R$12.49 per month with 1 GB. If the workers run out of memory, the app stops and does not come back on its own: lower the workers or raise the RAM and start it again. See the details of Python hosting.

API hosting

APIs in always-on containers, with no cold starts

Python hosting

FAQs

Is FastAPI faster than Flask?

For many requests waiting on I/O at the same time, FastAPI has a structural edge: it runs on ASGI and supports async end to end. Flask's docs say each request still ties up one worker, even in an async view. If the API mostly waits on the database, the number of workers and the queries matter more than the framework.

Do I need Django REST Framework to build an API with Django?

It is not required: a Django view can return a JsonResponse. DRF adds serializers with validation, authentication, permissions, pagination and the browsable API, which saves you from rewriting all of that by hand.

Can I use Django with async?

Yes. Django supports async views and runs under ASGI, and most ORM queries have async variants prefixed with a, such as acreate. According to the docs, transactions do not work in async mode, and the recommendation is to wrap them in a sync function called with sync_to_async.

Which server should I use in production?

Uvicorn for FastAPI (the fastapi run command uses it) and Gunicorn for Flask and Django. Each framework's development server is not built for production.

Is Flask still worth it for a new API?

Yes for small services, webhooks, prototypes and for people who already know Flask. Validation, OpenAPI docs and an ORM come from extensions you pick and maintain.

Next articleBest backend language: Node.js, Python, Go, Java or RustThere is no single best: Node.js and Python ship fast, Go makes concurrency simple, Java brings the JVM and Rust gives memory control. Compare them and pick.