Flask vs FastAPI vs Django: Choosing a Framework
Every Python web framework does the same four jobs: match a URL to code, parse and validate the incoming request, call your logic, and turn the result into a response with the right status and headers. What differs is how much of the surrounding work the framework owns â validation, ORM, admin, templating, background jobs â and how much freedom it leaves you. Choosing well means knowing which of those responsibilities you want to keep and which you would rather buy.
What You'll Learn
- 1Trace a request from URL match to response in a minimal and a batteries-included framework
- 2Write equivalent endpoints in Flask, FastAPI, and Django
- 3Compare validation, async support, and project layout across the three
- 4Pick a framework from project constraints rather than from popularity
The lifecycle every framework shares
A request arrives, the framework consults its router in registration order, and the first matching rule wins. Path and query parameters are converted to Python values, the body is parsed according to the content type, and any registered hooks run â before-request middleware, authentication, logging. Your view function executes and returns data, which is serialised into a response; an unhandled exception travels to an error handler that maps it to a status code.
Where the three diverge is in when work happens. Flask parses lazily and validates nothing, so mistakes surface at the point of use inside your code. FastAPI validates the request against a Pydantic model before your function is called, which means an invalid payload never reaches business logic and the OpenAPI document is generated from the same declarations. Django parses forms and files eagerly and ships an ORM, admin, and auth system that assume a conventional relational application.
Flask: the smallest shape that still works
Flask's contribution is a routing table, a request proxy, and a response pipeline, plus blueprints for splitting an application into modules. Everything else â validation, serialization, database access â is a library you choose.
from flask import Flask, jsonify, request, abort
app = Flask(__name__)
USERS = {1: {"name": "Alice", "role": "admin"}}
@app.get("/users")
def list_users():
limit = request.args.get("limit", default=10, type=int)
if not 1 <= limit <= 100:
abort(400, description="limit must be between 1 and 100")
return jsonify(list(USERS.values())[:limit])
@app.post("/users")
def create_user():
payload = request.get_json(silent=True) or {}
name = payload.get("name")
if not isinstance(name, str) or not name.strip():
return jsonify({"error": "name is required"}), 400
user_id = max(USERS) + 1
USERS[user_id] = {"name": name.strip(), "role": "member"}
return jsonify(USERS[user_id]), 201
@app.get("/users/<int:user_id>")
def get_user(user_id):
user = USERS.get(user_id)
if user is None:
abort(404)
return jsonify(user)
The manual validation in the example is the honest cost of that freedom: every check is written by hand, every error shape is invented, and consistency across endpoints depends on discipline. Flask suits services with a thin HTTP surface, teams that prefer explicit libraries, and codebases where the framework should stay out of the way.
FastAPI: validation before your function runs
FastAPI declares the contract once â Pydantic models for the body, typed parameters for the path and query â and the framework performs parsing, validation, error responses, and documentation from that declaration. Async endpoints are first-class, so an endpoint that awaits a database driver or an HTTP client does not block an event loop thread.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
app = FastAPI()
class UserIn(BaseModel):
name: str = Field(min_length=1, max_length=80)
email: str = Field(pattern=r"^[^@\s]+@[^@\s]+\.[A-Za-z]{2,}$")
role: str = Field(default="member", pattern=r"^(admin|member)$")
class UserOut(UserIn):
id: int
@app.get("/users", response_model=list[UserOut])
async def list_users(limit: int = 10):
if not 1 <= limit <= 100:
raise HTTPException(status_code=400, detail="limit must be 1..100")
return [{"id": i, "name": "Ada", "email": "[email protected]", "role": "admin"}
for i in range(1, limit + 1)]
@app.post("/users", response_model=UserOut, status_code=201)
async def create_user(user: UserIn):
return {"id": 99, **user.model_dump()}
Note what disappeared: manual type coercion, hand-written 400 responses, and a separately maintained API document. The trade-off is that Pydantic and FastAPI become structural dependencies â models appear in your view signatures, and swapping them out later is a rewrite rather than a refactor.
Django: the conventional application
Django assumes a relational application with users, an admin, and server-rendered templates, and it delivers all of them. The view layer spans three flavours: class-based views for common shapes, function views for explicit control, and Django REST Framework when you are building an API.
# models.py
from django.db import models
class User(models.Model):
name = models.CharField(max_length=80)
email = models.EmailField(unique=True)
role = models.CharField(max_length=16, default="member")
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["-created_at"]
# views.py
from django.http import JsonResponse
from django.views.decorators.http import require_GET
from .models import User
@require_GET
def list_users(request):
try:
limit = int(request.GET.get("limit", 10))
except ValueError:
return JsonResponse({"error": "limit must be an integer"}, status=400)
if not 1 <= limit <= 100:
return JsonResponse({"error": "limit must be 1..100"}, status=400)
rows = User.objects.all()[:limit]
return JsonResponse(
[{"id": u.id, "name": u.name, "email": u.email, "role": u.role}
for u in rows],
safe=False,
)
Models come with migrations, the ORM handles joins and transactions, and the admin console is generated from the model definitions. For a team building a product with CRUD, permissions, and content management, that default is the entire argument.
Choosing from the project, not the trend
| Concern | Flask | FastAPI | Django |
|---|---|---|---|
| Validation | Manual or an added library | Built in via Pydantic | Forms and serializers |
| Async | Possible with an ASGI server | Native and idiomatic | Supported, ORM still blocking |
| Database | Your choice, no default | Your choice, no default | ORM included |
| Docs | Add Flask-RESTx or similar | OpenAPI generated for free | DRF provides it |
| Admin | None | None | Included |
| Best fit | Small services, APIs you shape yourself | Typed APIs, async fan-out, generated clients | Full products with auth, admin, and content |
Pick Flask when the HTTP layer is thin and you want the library list to be yours. Pick FastAPI when the API is the product's contract and you want types, validation, and client generation to come from one source. Pick Django when you are building a conventional application and would rather write domain logic than assemble infrastructure. A useful tiebreaker: sketch the endpoints you need in each, and choose the one where the sketch already contains fewer decisions.
Testing the HTTP layer without ceremony
All three frameworks ship a test client that exercises routing, parsing, and serialisation without binding a socket, which makes endpoint tests fast enough to run on every change. The habit that keeps them useful is asserting on the contract rather than on internals: status code, response shape, and the state change you intended, with nothing about the framework's own objects in the assertion.
Flask gives you app.test_client(), FastAPI gives TestClient, and Django wraps its client in pytest-django or the built-in TestCase. In each case the test builds the application with test configuration, issues a request, and inspects the response â the same three steps, so a test written against one framework transfers almost unchanged to another. Keep the database out of the way with a transaction fixture or an in-memory engine, and use a fake for any external HTTP call so the suite stays deterministic.
Integration coverage still matters at the edges: one test that boots the real application with production-like configuration catches mistakes that a suite of view tests cannot, such as a missing environment variable, an unregistered middleware, or a static file rule that shadows an API route.
Layout and settings that age well
Whichever you choose, the structure that survives growth is the same: keep configuration in the environment, split the application by domain rather than by file type, and put business logic somewhere a view cannot reach directly. In Flask that means blueprints plus a service module; in FastAPI, routers plus dependency functions for anything shared; in Django, an app per domain with thin views over a service layer.
Settings deserve special care because they are where staging and production diverge. Read the debug flag, secret key, database URL, and third-party credentials from the environment with loud failure when a required value is missing, never from a file that ships in the image. Separate the configuration surface into development, test, and production profiles early; retrofitting it after an incident is far more expensive than doing it in the first week.
Common Mistakes
Returning ad-hoc error strings from every endpoint
Fix: Define one error envelope and one exception handler so clients can parse failures without per-endpoint rules
Putting business logic inside view functions
Fix: Move it into a service module the views call; it becomes testable without an HTTP client and reusable from jobs
Reading secrets and flags from a settings file committed to the repository
Fix: Load configuration from the environment and fail fast when a required variable is absent
Choosing a framework because it is popular rather than because its defaults match the project
Fix: Sketch your endpoints in each candidate and pick the one with the fewest unmade decisions
Best Practices
- Validate at the boundary with a schema so invalid requests never reach business logic
- Return consistent status codes and one error shape across the whole API
- Keep framework objects out of your domain layer so the core can be tested without a server
- Generate API documentation from declarations instead of maintaining it by hand
- Run the same smoke test against development and production configuration to catch environment drift early
Interview Questions
Q1: What does FastAPI gain by requiring Pydantic models?
One declaration drives parsing, validation, error responses, serialisation, and the OpenAPI document, so the contract cannot drift from the implementation and invalid payloads are rejected before business logic runs.
Q2: When would you choose Flask over FastAPI?
When the surface is small, validation needs are simple, and the team wants explicit control over libraries rather than a framework that dictates a modelling style. Also when an existing extension ecosystem already covers the requirement.
Q3: Why separate views from service logic?
Views handle HTTP concerns â status codes, headers, parsing â while services hold business rules. Keeping them apart makes the rules testable without a running server and lets jobs or CLI tools reuse them.
Q4: What is the practical difference between ASGI and WSGI here?
WSGI servers run one request per worker thread or process, so long-lived connections tie up capacity. ASGI supports async handlers and WebSockets, which is why FastAPI can await thousands of idle requests on one loop.
Key Takeaways
- All three frameworks share routing, parsing, and response handling; they differ in how much surrounding work they own
- Flask gives freedom and charges in hand-written validation, FastAPI buys consistency from typed declarations, Django buys an ecosystem
- Async support matters only when your dependencies have async clients; the framework cannot make a blocking driver non-blocking
- Keep configuration in the environment and business logic outside the view layer regardless of framework
- Choose from project constraints â team, timeline, admin needs, async needs â rather than from popularity