/compare/flask/flask-vs-fastapi
Flask vs FastAPI: differences for building Python web APIs
- tool
- Flask
- compares
- Flask vs FastAPI
Both are small Python frameworks for HTTP APIs. Flask is a mature WSGI micro-framework: routing and request handling, with validation, serialization and API documentation added through extensions. FastAPI is an ASGI framework built on Starlette and Pydantic: it is async-first, validates requests from type hints, and generates OpenAPI documentation automatically.
Criterion by criterion
| Criterion | Flask | FastAPI |
|---|---|---|
| Server interface | WSGI (gunicorn, uWSGI) | ASGI (uvicorn, hypercorn) |
| async views | supported, but each request still uses a worker thread | native; designed for async I/O |
| Request validation | manual or via extensions (marshmallow, pydantic) | built in, from type hints via Pydantic |
| API documentation | extensions (flask-smorest, apispec) | automatic OpenAPI with /docs and /redoc |
| Templates and HTML apps | Jinja2 built in, many extensions | possible (Jinja2 via Starlette), API-focused |
| Maturity and ecosystem | since 2010, large extension ecosystem | since 2018, fast-growing |
The same endpoint in Flask, tested
python -c '
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.post("/items")
def create_item():
data = request.get_json(silent=True) or {}
if not isinstance(data.get("price"), (int, float)):
return jsonify(error="price must be a number"), 422
return jsonify(name=data.get("name"), price=data["price"]), 201
client = app.test_client()
for body in ({"name": "pen", "price": 1.5}, {"name": "pen", "price": "free"}):
r = client.post("/items", json=body)
print(r.status_code, r.get_json())'Output
201 {'name': 'pen', 'price': 1.5}
422 {'error': 'price must be a number'}The same endpoint in FastAPI
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.post("/items", status_code=201)
def create_item(item: Item):
return itemThe validation that Flask does by hand comes from the Item model: an invalid price gets a 422 response with a detailed error, and the endpoint appears in /docs.
Which one
Choose FastAPI for new JSON APIs with many endpoints, async database or HTTP calls, and a need for accurate API docs. Choose Flask when you render HTML, rely on its extensions, or already run WSGI infrastructure.