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
pip install flask
A minimal Hello World app
app.py
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:
# 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:
@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 anintautomatically, 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), anduuid.
Reading query strings
Query string parameters (the part after ? in a URL) are read from request.args, which behaves like a dictionary:
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})"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:
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"
}