PythonIntro to Flask

Intro to Flask

Flask is a lightweight, "micro" web framework for Python. Micro doesn't mean limited — it means Flask itself only provides the essentials (routing, request/response handling, templating) and stays deliberately unopinionated about everything else. There's no built-in ORM, no built-in admin panel, no prescribed project layout — you add exactly the pieces you need, as separate libraries, when you need them. That makes Flask a great fit for small APIs, microservices, and getting an idea running quickly.

Installing Flask

Bash
pip install flask
A minimal Hello World app

app.py

Python
from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Hello, World!"

if __name__ == "__main__":
    app.run(debug=True)
Running the development server

There are two common ways to start the built-in dev server. Either run the script directly (since it calls app.run() itself), or use the flask command, pointing it at the module via an environment variable:

Bash
# Option 1: run the script directly
python app.py

# Option 2: use the flask CLI
export FLASK_APP=app.py
flask run --debug
 * Running on http://127.0.0.1:5000
 * Debug mode: on

debug=True (or --debug) enables auto-reload on code changes and shows detailed tracebacks in the browser on errors — invaluable during development, but it should always be turned off in production.

Dynamic URL parameters

Routes can capture parts of the URL directly as function arguments by naming them inside angle brackets, optionally with a type converter:

Python
@app.route("/users/<int:user_id>")
def get_user(user_id):
    # user_id is already an int here, not a string
    return f"User #{user_id}"

@app.route("/posts/<slug>")
def get_post(slug):
    return f"Post: {slug}"
  • <int:user_id> converts the URL segment to an int automatically, and the route only matches if it looks like a number.

  • <slug> with no converter is treated as a plain string.

  • Other built-in converters include float, path (allows slashes), and uuid.

Reading query strings

Query string parameters (the part after ? in a URL) are read from request.args, which behaves like a dictionary:

Python
from flask import request

@app.route("/search")
def search():
    query = request.args.get("q", "")
    page = request.args.get("page", 1, type=int)
    return f"Searching for '{query}' (page {page})"

Bash
curl "http://127.0.0.1:5000/search?q=flask&page=2"
Searching for 'flask' (page 2)
Returning JSON

For APIs, use jsonify() to turn a Python dict (or list) into a proper JSON response with the correct Content-Type header set:

Python
from flask import jsonify

@app.route("/api/users/<int:user_id>")
def api_get_user(user_id):
    return jsonify({
        "id": user_id,
        "name": "Ada Lovelace",
        "active": True,
    })
{
  "active": true,
  "id": 1,
  "name": "Ada Lovelace"
}
Flask vs Django
Flask is a good fit when you want a small, focused API or microservice, or when you're prototyping and don't want a framework making structural decisions for you. If your project is going to grow into something with user accounts, an admin interface, and a database-backed data model from day one, it's worth comparing to **Django**, which bundles all of that in.