Table of Contents
What Is Flask?
Flask is a lightweight web framework for Python. A web framework is a set of tools that makes it easier to build websites and web applications without handling every low-level detail yourself.
Flask is often called a “micro-framework” because:
- It gives you the basics: handling web requests and sending responses.
- It doesn’t force you to use a specific database or structure.
- You can add extra features (like forms, authentication, databases) using extensions when you need them.
Flask is great for beginners because:
- It’s simple to get started.
- A basic app can be only a few lines of code.
- You see results in your browser quickly.
Typical things you can do with Flask:
- Serve web pages (HTML).
- Create APIs that send and receive data (JSON).
- Build small web tools, dashboards, or prototypes.
Installing Flask
You install Flask like any other Python library, usually using pip.
It’s best practice to work in a virtual environment, but here the focus is on Flask itself. A minimal way to install:
pip install flask
If you want to be explicit and you’re using python:
python -m pip install flaskTo check that Flask is installed correctly, you can run in Python interactive mode:
>>> import flask
>>> flask.__version__
'3.0.0' # your version may be differentYour First Flask App
A minimal Flask application is surprisingly short. Create a new file called app.py and put this inside:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, Flask!"Line by line:
from flask import Flask
Imports the main Flask class from theflaskpackage.app = Flask(__name__)
Creates a Flask application object.__name__tells Flask where your app is defined (used for locating templates, static files, etc.).@app.route("/")
This is a route decorator. It tells Flask: “When someone visits the/URL (the home page), call the function below.”def home():
Defines a view function that runs when a user visits/.return "Hello, Flask!"
Whatever this function returns is sent as the HTTP response to the browser. Here, it’s just plain text.
Running a Flask Development Server
Flask includes a built-in development server. It’s not meant for production, but it’s perfect while learning.
Using the `flask` command
- Make sure
app.pyis in your current folder. - In your terminal, set the app name (on macOS/Linux):
export FLASK_APP=app.py
flask runOn Windows (Command Prompt):
set FLASK_APP=app.py
flask run- You should see output like:
* Serving Flask app 'app.py'
* Running on http://127.0.0.1:5000- Open a browser and go to
http://127.0.0.1:5000/.
You should see:Hello, Flask!.
Enabling Debug Mode (Auto-Reload)
Debug mode automatically restarts the server when you change the code and can show detailed error pages.
To turn it on:
macOS/Linux:
export FLASK_APP=app.py
export FLASK_ENV=development # for older Flask, or:
export FLASK_DEBUG=1 # for newer
flask runWindows (Command Prompt):
set FLASK_APP=app.py
set FLASK_ENV=development
flask runWith debug mode on:
- When you edit and save
app.py, Flask will reload automatically. - If there’s an error, you see a helpful debug page in the browser.
Understanding Routes and View Functions
Flask maps URLs (like /, /about, /hello) to Python functions. Each mapping is called a route.
Basic pattern:
@app.route("/some-path")
def some_name():
return "Something to show"Examples of multiple routes:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Home page"
@app.route("/about")
def about():
return "About this site"
@app.route("/contact")
def contact():
return "Contact page"Now:
http://127.0.0.1:5000/→ shows “Home page”http://127.0.0.1:5000/about→ shows “About this site”http://127.0.0.1:5000/contact→ shows “Contact page”
Dynamic Routes with Variables
Sometimes, you want the URL to contain a variable part, like a username or an item id.
You can define a dynamic route using <variable_name>:
from flask import Flask
app = Flask(__name__)
@app.route("/hello/<name>")
def hello(name):
return f"Hello, {name}!"- Visiting
/hello/Alex→ “Hello, Alex!” - Visiting
/hello/Sam→ “Hello, Sam!”
Flask tries to match the <name> part to the function parameter name.
You can also specify a type, for example:
<int:age>for integers<float:score>for floating-point numbers
Example:
@app.route("/age/<int:age>")
def show_age(age):
return f"You are {age} years old."
Now /age/30 works, but /age/thirty will not match this route because thirty is not an integer.
Returning HTML Instead of Plain Text
So far, we’ve returned plain text. Browsers can also display HTML, which is how you build real web pages.
A simple HTML response:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return """
<html>
<head>
<title>My First Flask Page</title>
</head>
<body>
<h1>Welcome!</h1>
<p>This is a simple HTML page from Flask.</p>
</body>
</html>
"""This is a quick way to get started, but in practice you’ll usually use templates (separate HTML files). Templates are covered in the “Routing and templates” chapter, so here we just show the inline idea.
Using `request` Data (Basic Idea)
For more interactive pages, the server needs to read information sent by the browser (e.g. form data, query parameters). Flask lets you access this using the request object.
A very simple example using query parameters (the part after ? in a URL):
from flask import Flask, request
app = Flask(__name__)
@app.route("/greet")
def greet():
name = request.args.get("name", "stranger")
return f"Hello, {name}!"Now:
/greet→ “Hello, stranger!”/greet?name=Alex→ “Hello, Alex!”
We will go deeper into handling forms and user input in later sections, but this shows how Flask connects URLs, data, and Python code.
Common Folder Structure (Basic Overview)
Even for small apps, it’s useful to know the typical layout of a Flask project. A very common minimal structure is:
your_project/
app.py
templates/
static/Typical uses:
app.py– main Flask application file.templates/– HTML templates (used with Flask’s templating system).static/– static files like CSS, JavaScript, and images.
In this introduction, we’re mostly working with app.py. The “Routing and templates” chapter will show how to use templates/ and static/ in detail.
A Tiny Example App: “Mini Homepage”
Putting it all together, here’s a small app with multiple routes and a dynamic route:
from flask import Flask, request
app = Flask(__name__)
@app.route("/")
def home():
return """
<h1>Welcome to My Site</h1>
<p>Try visiting <a href="/about">/about</a> or <a href="/hello?name=Alex">/hello?name=Alex</a>.</p>
"""
@app.route("/about")
def about():
return "<h2>About</h2><p>This is a tiny Flask app example.</p>"
@app.route("/hello")
def hello():
name = request.args.get("name", "friend")
return f"<h2>Hello, {name}!</h2>"Steps to run:
- Save as
app.py. - Install Flask with
pip install flaskif you haven’t. - Set
FLASK_APP=app.pyin your terminal. - Run
flask run. - Visit:
/for the home page/aboutfor the about page/hello?name=YourNameto see a personalized greeting.
Summary
In this introduction to Flask, you’ve seen:
- What Flask is and why it’s useful for web development with Python.
- How to install Flask using
pip. - How to write and run a minimal Flask app with
app.py. - How routes map URLs to Python functions.
- How to define static and dynamic routes (with variables).
- How to return plain text and simple HTML.
- A glimpse of using
requestto read data from the URL.
Next, you’ll learn how to create more structured pages using templates, handle user input with forms, and build more capable web applications.