Introduction
Flask is the classic Python web framework — minimal, flexible, and battle-tested. Even in 2026, it’s everywhere. This post builds a REST API with Flask and gives an honest comparison with FastAPI so you can choose.
Setup
pip install flask
Step 1: Hello World API
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/")
def home():
return jsonify({"message": "Hello, World!"})
if __name__ == "__main__":
app.run(debug=True, port=5000)
Run: python app.py. Visit http://localhost:5000.
Step 2: CRUD endpoints
from flask import Flask, jsonify, request
app = Flask(__name__)
notes = [] # in-memory (use a DB in production)
@app.route("/notes", methods=["GET"])
def list_notes():
return jsonify(notes)
@app.route("/notes", methods=["POST"])
def create_note():
data = request.get_json()
if not data or "title" not in data:
return jsonify({"error": "title required"}), 400
note = {"id": len(notes) + 1, "title": data["title"], "body": data.get("body", "")}
notes.append(note)
return jsonify(note), 201
@app.route("/notes/<int:note_id>", methods=["GET"])
def get_note(note_id):
note = next((n for n in notes if n["id"] == note_id), None)
if not note:
return jsonify({"error": "not found"}), 404
return jsonify(note)
@app.route("/notes/<int:note_id>", methods=["DELETE"])
def delete_note(note_id):
global notes
notes = [n for n in notes if n["id"] != note_id]
return "", 204
Step 3: Error handling
@app.errorhandler(404)
def not_found(e):
return jsonify({"error": "Resource not found"}), 404
@app.errorhandler(500)
def server_error(e):
return jsonify({"error": "Internal server error"}), 500
Step 4: Blueprints (modular routes)
# routes/notes.py
from flask import Blueprint, jsonify, request
notes_bp = Blueprint("notes", __name__, url_prefix="/notes")
@notes_bp.route("/", methods=["GET"])
def list_notes():
return jsonify([])
# app.py
from routes.notes import notes_bp
app.register_blueprint(notes_bp)
Blueprints keep large apps organized — one file per resource.
Step 5: Middleware and hooks
@app.before_request
def log_request():
print(f"{request.method} {request.path}")
@app.after_request
def add_headers(response):
response.headers["X-Custom-Header"] = "value"
return response
Step 6: CORS (for frontend apps)
pip install flask-cors
from flask_cors import CORS
CORS(app, origins=["http://localhost:3000"])
Step 7: Testing
import pytest
from app import app
@pytest.fixture
def client():
app.config["TESTING"] = True
return app.test_client()
def test_create_note(client):
r = client.post("/notes", json={"title": "Test"})
assert r.status_code == 201
assert r.json["title"] == "Test"
def test_get_note(client):
client.post("/notes", json={"title": "Test"})
r = client.get("/notes/1")
assert r.status_code == 200
Flask’s test_client() makes testing easy — no server needed.
Step 8: Deployment
pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:8000 app:app
4 workers, binding to port 8000. Use behind nginx (see Docker post).
Flask vs FastAPI (2026)
| Flask | FastAPI | |
|---|---|---|
| Async support | Limited (via extensions) | Native (async/await) |
| Auto docs (Swagger) | No (add flasgger) | Yes (built-in) |
| Validation | Manual (or marshmallow) | Automatic (Pydantic) |
| Performance | Good (WSGI) | Excellent (ASGI) |
| Ecosystem | Massive (10+ years) | Growing fast |
| Learning curve | Easy | Easy |
| Type hints | Optional | Core feature |
| WebSockets | Via extensions | Built-in |
| Background tasks | Via Celery | Built-in (BackgroundTasks) |
Choose Flask when:
- You’re maintaining an existing Flask app.
- You need a specific Flask extension.
- Your team knows Flask and the app is simple.
- You’re building a traditional server-rendered app (with Jinja2).
Choose FastAPI when:
- Building a new API (especially async).
- You want auto-generated docs.
- You need high performance (async I/O).
- You’re building microservices.
- Type safety matters.
Common mistakes
- No input validation — Flask doesn’t validate. Use
marshmalloworpydanticmanually. - Using
app.run()in production — it’s a dev server. Use Gunicorn/uWSGI. - Global state —
notes = []in module scope breaks with multiple workers. Use a database. - No CORS — frontend apps on different origins will fail. Add
flask-cors. - Debug mode in production —
debug=Trueexposes a debugger. Never in prod.
Key Concepts
- Flask = micro web framework (routing, request/response)
- Blueprint = modular route grouping
request.get_json()= parse JSON bodyjsonify= convert dict to JSON response- Gunicorn = production WSGI server
- CORS = cross-origin resource sharing
What to Try Next
- Add SQLAlchemy for a real database.
- Add JWT auth with Flask-JWT-Extended.
- Deploy with Docker.
- Compare with FastAPI by porting the same app.
FAQ
Flask or FastAPI for a new project in 2026?
FastAPI for APIs (async, docs, validation built in). Flask for traditional web apps (server-rendered with Jinja2) or when you need Flask-specific extensions. When in doubt, FastAPI.
Is Flask dead?
No — it’s still widely used and maintained. But new projects increasingly choose FastAPI. Flask’s ecosystem (extensions, tutorials, StackOverflow) remains unmatched. It’s “legacy but alive.”
Can Flask do async?
Flask 2.0+ supports async views (async def), but it’s not as native as FastAPI. For heavy async I/O, FastAPI is better. For light async, Flask works.