PYTHON APPLIEDChapter 12 · Python for Web Development
Building routes with Flask
Flask is a lightweight Python web framework. You define routes that map URL paths to Python functions. Each route function returns a response, often as JSON data that a frontend can consume.
Worked example
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/api/stars")
def get_stars():
stars = ["Vega", "Sirius", "Polaris"]
return jsonify(stars)
# Run with: flask run
# Visit: http://localhost:5000/api/starsHow it reads
- @app.route("/api/stars") maps the URL path to the function below it
- jsonify(stars) converts a Python list into a JSON HTTP response
- Flask(__name__) creates the application instance

Cloud tip: Flask is called a 'micro' framework because it gives you only the essentials. You add extensions (like Flask-SQLAlchemy) as you need them.


