Python for Data & Web
Python Flask Basics
Flask is a lightweight Python web framework that lets you build a working web app or API in just a handful of lines, making it a favourite starting point for beginners.
Installing Flask
Flask is a third-party package, so install it with pip inside your project first.
pip install flaskA Minimal Flask App
Every Flask app starts with a Flask instance and one or more routes — functions connected to a URL using the @app.route decorator. When someone visits that URL, the matching function runs and its return value becomes the response.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello from Flask!"
if __name__ == "__main__":
app.run(debug=True)python app.pyWith debug=True, Flask auto-reloads whenever you save the file and shows helpful error pages, which is great while learning — just remember to switch it off before deploying to production.
Returning JSON
For an API endpoint, return a Python dictionary and Flask automatically converts it to a proper JSON response using jsonify.
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/api/status")
def status():
return jsonify({"status": "ok", "service": "myinternships"})Dynamic Routes
You can capture parts of the URL as variables by wrapping a name in angle brackets in the route, letting one function handle many different URLs.
@app.route("/user/<username>")
def show_user(username):
return f"Profile page for {username}"
@app.route("/job/<int:job_id>")
def show_job(job_id):
return jsonify({"job_id": job_id})Adding <int:job_id> instead of just <job_id> tells Flask to convert the value to an integer automatically and only match numeric URLs.
Flask functions can also handle forms, files, and different HTTP methods like POST using the methods argument in @app.route.
