Web frameworks · Beginner · 20 min
Build your first web app with Flask 3
By Padding · Updated 18 Nov 2026
Python 3.15 (python:3.15-slim) · Flask 3.1.3 · uv 0.13
You will build a small guestbook in Flask 3.1 on Python 3.15, with routes, Jinja templates that share a layout, a static stylesheet, a validated POST form, flash messages and a redirect after each post.
On this page
Flask is a small Python web framework. Out of the box it gives you URL routing, request and response objects, Jinja templates, signed cookie sessions and a development server, and very little else. There is no database layer, admin or form library until you add one. That makes it quick to learn: a whole app can live in one file, and you can see every moving part.
In this tutorial you build a guestbook. Visitors read the entries on the home page, open one entry on its own page, and sign the book with a form. Entries are kept in a Python list, so they disappear when the server restarts; the follow-up tutorial moves them into a database. You use uv for the project, as in the Python series. If you have not set it up, start with the Python install tutorial.
Step 1 · Create the project and install Flask
Make a throwaway folder, start a uv project in it and add Flask. The exact version is pinned so the output you see matches this page:
mkdir -p ~/guestbook-demo
cd ~/guestbook-demo
uv init --no-package
rm main.py
uv add "flask==3.1.3"
uv run flask --versionuv creates a .venv folder, installs Flask with its dependencies (Werkzeug for HTTP, Jinja for templates, MarkupSafe for escaping, Click for the command line, ItsDangerous for signing cookies) and records them in pyproject.toml and uv.lock.
Check it worked
flask --version prints three lines: the Python version (3.15 and a patch number), Flask 3.1.3 and the Werkzeug version. If you see command not found, run the command from inside ~/guestbook-demo, where uv can find the project.
Step 2 · Write your first page and run the debug server
A Flask app is an object, and each page is a function registered for a URL. Create app.py:
cat > app.py <<'PY'
from flask import Flask
app = Flask(__name__)
@app.get("/")
def index():
return "<h1>Guestbook</h1><p>No entries yet.</p>"
PYFlask(__name__) tells Flask where the app lives, so it can find the templates and static folders next to it later. @app.get("/") registers index for GET requests to the home page. Whatever the function returns becomes the response body.
In your second terminal, go to ~/guestbook-demo and start the development server in debug mode:
uv run flask --app app run --debug--app app names the module that holds the app. Debug mode turns on two things: the reloader, which restarts the server each time you save a Python file, and the interactive debugger, which shows a traceback in the browser when your code raises an error. The server listens on 127.0.0.1:5000, which only your own computer can reach. Back in the first terminal, request the page:
curl -s http://127.0.0.1:5000/Check it worked
curl prints <h1>Guestbook</h1><p>No entries yet.</p>. The server terminal shows Debug mode: on, the address it is running on, a debugger PIN and a log line for your request ending in 200. You can also open http://127.0.0.1:5000/ in a browser.
If the server says the address is already in use on a Mac, macOS Monterey and later run a system service on port 5000. Add --port 5001 to the run command and use that port in the URLs instead.
Step 3 · Add routes with variable parts
Parts of a URL can be variables. Flask passes them to your function as arguments, and a converter such as int only accepts the URL when that part is a whole number. Replace app.py:
cat > app.py <<'PY'
from flask import Flask
from markupsafe import escape
app = Flask(__name__)
@app.get("/")
def index():
return "<h1>Guestbook</h1><p>No entries yet.</p>"
@app.get("/hello/<name>")
def hello(name):
return f"<p>Hello, {escape(name)}.</p>"
@app.get("/entries/<int:entry_id>")
def show_entry(entry_id):
return f"<p>You asked for entry {entry_id}.</p>"
PY<name> matches any text without a slash. escape() turns <, >, & and quotes into HTML entities, which matters whenever you put text from a visitor into HTML by hand. A URL is visitor input like any other. Save the file and the debug server reloads by itself.
List the routes Flask now knows, then try each one:
uv run flask --app app routes
curl -s http://127.0.0.1:5000/hello/Amara
curl -s http://127.0.0.1:5000/hello/%3Cb%3EAmara
curl -s http://127.0.0.1:5000/entries/7
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:5000/entries/sevenCheck it worked
flask routes lists the endpoints hello, index, show_entry and static with their methods and URL rules. The curl commands print, in order: <p>Hello, Amara.</p>, <p>Hello, <b>Amara.</p> (the tag arrives as text, not markup), <p>You asked for entry 7.</p> and 404. The last one never reaches your function: the int converter rejects seven before Flask calls it.
Step 4 · Render pages with Jinja templates
Building HTML in Python strings does not scale. Jinja templates keep the HTML in their own files, and template inheritance lets every page share one layout. Flask looks for templates in a templates folder next to app.py. Create the layout first:
mkdir -p templates
cat > templates/base.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}Guestbook{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<main>
{% block content %}{% endblock %}
</main>
</body>
</html>
HTMLEach {% block %} is a slot that a child template can fill. url_for('static', ...) builds the URL of a static file, which you create in the next step. Now the two pages. Each one starts with {% extends "base.html" %} and fills only the blocks it needs:
cat > templates/index.html <<'HTML'
{% extends "base.html" %}
{% block content %}
<h1>Guestbook</h1>
<ol class="entries">
{% for entry in entries %}
<li><a href="{{ url_for('show_entry', entry_id=loop.index) }}">{{ entry.name }}</a>: {{ entry.message }}</li>
{% else %}
<li>No entries yet.</li>
{% endfor %}
</ol>
{% endblock %}
HTML
cat > templates/entry.html <<'HTML'
{% extends "base.html" %}
{% block title %}{{ entry.name }} · Guestbook{% endblock %}
{% block content %}
<p><a href="{{ url_for('index') }}">All entries</a></p>
<h1>{{ entry.name }}</h1>
<p>{{ entry.message }}</p>
{% endblock %}
HTML{{ ... }} prints a value and {% ... %} runs logic. loop.index counts from 1, which gives each entry its number. The {% else %} branch of a for loop runs when the list is empty. Replace app.py so the views render these templates. Two sample entries stand in for real data for now, and the second has HTML in it on purpose. The hello route has done its job and is gone:
cat > app.py <<'PY'
from flask import Flask, abort, render_template
app = Flask(__name__)
entries = [
{"name": "Amara", "message": "Hello from Lagos."},
{"name": "Tester", "message": "<em>Is this italic?</em>"},
]
@app.get("/")
def index():
return render_template("index.html", entries=entries)
@app.get("/entries/<int:entry_id>")
def show_entry(entry_id):
if not 1 <= entry_id <= len(entries):
abort(404)
return render_template("entry.html", entry=entries[entry_id - 1])
PYrender_template fills a template with the values you pass by name. abort(404) stops the request and sends Flask's Not Found page.
curl -s http://127.0.0.1:5000/
curl -s http://127.0.0.1:5000/entries/1 | grep -o '<title>[^<]*</title>'
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:5000/entries/3Check it worked
The home page comes back as a full HTML document with the layout's <head> and two list items linking to /entries/1 and /entries/2. The second message reads <em>Is this italic?</em>: Flask turns on auto-escaping for templates ending in .html, so every {{ }} value is escaped unless you mark it safe with the |safe filter. Never use |safe on anything a visitor typed. The entry page's title is <title>Amara · Guestbook</title>, and entry 3 returns 404.
Step 5 · Serve a stylesheet as a static file
Flask serves anything in a static folder next to app.py at /static/..., with no route to write. Create a small stylesheet:
mkdir -p static
cat > static/style.css <<'CSS'
body {
font-family: system-ui, sans-serif;
line-height: 1.5;
max-width: 40rem;
margin: 2rem auto;
padding: 0 1rem;
color: #1d1f23;
}
.entries li { margin-bottom: 0.5rem; }
.flash { background: #e9f2ec; padding: 0.5rem 0.75rem; border-radius: 4px; }
.error { color: #a1260d; }
label, input, textarea, button { display: block; font: inherit; }
input, textarea { width: 100%; margin-bottom: 0.75rem; }
CSS
curl -sI http://127.0.0.1:5000/static/style.cssThe layout already links to it through url_for, so every page picks it up. If you later move static files behind a CDN or a different path, url_for is the one place that changes, not every template.
Check it worked
The headers start with a 200 status and include Content-Type: text/css; charset=utf-8. Reload the home page in a browser: the text sits in a narrow centred column in the system font. The whole page is a few kilobytes of server-rendered HTML and CSS with no JavaScript, so it opens quickly on a low-end Android phone and costs little on prepaid mobile data.
Step 6 · Handle the form with flash messages and a redirect
Signing the guestbook needs a form that sends a POST request, code that checks what arrived, and a way to tell the visitor it worked. Flask's flash messages are stored in the session, a cookie that Flask signs with a secret key so visitors cannot change it. (They can still read it, so never put secrets in the session.) The app reads the key from an environment variable rather than from the code.
Stop the server with Ctrl+C. In the server terminal, generate a random key into the environment, then start the server again with the same uv run flask --app app run --debug command:
export FLASK_SECRET_KEY="$(uv run python -c 'import secrets; print(secrets.token_hex(32))')"The key lasts as long as that terminal session. A new key on each start logs everyone out, which is fine for development. On a server, load a fixed key from a protected file or a secrets manager. Now replace app.py. The sample entries go, and the home page accepts POST as well as GET:
cat > app.py <<'PY'
import os
from flask import Flask, abort, flash, redirect, render_template, request, url_for
app = Flask(__name__)
app.config["SECRET_KEY"] = os.environ["FLASK_SECRET_KEY"]
# Kept in memory: lost on restart, and not shared between server processes.
entries = []
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
name = request.form.get("name", "").strip()
message = request.form.get("message", "").strip()
error = None
if not name or not message:
error = "Please fill in your name and a message."
elif len(name) > 60 or len(message) > 500:
error = "Keep your name to 60 characters and your message to 500."
if error:
return render_template(
"index.html", entries=entries, error=error, name=name, message=message
), 400
entries.append({"name": name, "message": message})
flash("Thanks for signing the guestbook.")
return redirect(url_for("index"), code=303)
return render_template("index.html", entries=entries, name="", message="")
@app.get("/entries/<int:entry_id>")
def show_entry(entry_id):
if not 1 <= entry_id <= len(entries):
abort(404)
return render_template("entry.html", entry=entries[entry_id - 1])
PYrequest.form holds the submitted fields. The checks run on the server even though the HTML form below also marks the fields as required, because anyone can send a request without your form, as curl is about to show. A failed check renders the page again with status 400 and keeps what the visitor typed. A successful post stores the entry, queues a flash message and answers with a 303 See Other redirect to the home page. The browser then loads the home page with a GET, so pressing reload does not post the entry a second time. This pattern is called Post/Redirect/Get.
os.environ["FLASK_SECRET_KEY"] fails with a KeyError if the variable is missing, so the app refuses to start without a key instead of running with a guessable one.
Add the form to the home page:
cat > templates/index.html <<'HTML'
{% extends "base.html" %}
{% block content %}
<h1>Guestbook</h1>
<ol class="entries">
{% for entry in entries %}
<li><a href="{{ url_for('show_entry', entry_id=loop.index) }}">{{ entry.name }}</a>: {{ entry.message }}</li>
{% else %}
<li>No entries yet.</li>
{% endfor %}
</ol>
<h2>Sign the guestbook</h2>
<form method="post" action="{{ url_for('index') }}">
<label for="name">Name</label>
<input id="name" name="name" value="{{ name }}" maxlength="60" required>
<label for="message">Message</label>
<textarea id="message" name="message" rows="3" maxlength="500" required>{{ message }}</textarea>
{% if error %}<p class="error">{{ error }}</p>{% endif %}
<button type="submit">Sign</button>
</form>
{% endblock %}
HTMLThen show flash messages in the layout, so any page can display them. Replace templates/base.html:
cat > templates/base.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}Guestbook{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<main>
{% for message in get_flashed_messages() %}
<p class="flash">{{ message }}</p>
{% endfor %}
{% block content %}{% endblock %}
</main>
</body>
</html>
HTMLget_flashed_messages() returns the queued messages and removes them from the session, so each one shows once.
Sign the book from the command line. The name and message are in Yorùbá, to check that text with tone marks survives the round trip. curl's cookie jar plays the part of the browser's cookies:
curl -s -D - -o /dev/null -c cookies.txt -b cookies.txt \
--data-urlencode 'name=Adébáyọ̀' \
--data-urlencode 'message=Ẹ kú iṣẹ́ o. Lovely site.' \
http://127.0.0.1:5000/
curl -s -c cookies.txt -b cookies.txt http://127.0.0.1:5000/ | grep -E 'class="flash"|Adébáyọ̀'Now try the two things the server must refuse to trust: an empty form and a message with a script in it:
curl -s -o /dev/null -w '%{http_code}\n' -d 'name=&message=' http://127.0.0.1:5000/
curl -s -o /dev/null --data-urlencode 'name=Mallory' --data-urlencode 'message=<script>alert(1)</script>' http://127.0.0.1:5000/
curl -s http://127.0.0.1:5000/ | grep -o 'Mallory</a>: [^<]*'Check it worked
The first command prints only the response headers. They show a 303 status and a Location header pointing at /, plus a Set-Cookie header for the session. The second prints the <p class="flash">Thanks for signing the guestbook.</p> line and the entry with Adébáyọ̀ spelt exactly as typed. Request the home page again and the flash message is gone. The empty form returns 400, and Mallory's entry reads <script>alert(1)</script>, so it shows as text and never runs.
In a browser, fill in the form and press Sign: the page reloads with the green message above the list. Press reload afterwards and nothing is posted twice.
One protection is still missing for a real site: Flask has no built-in defence against cross-site request forgery (CSRF), where another site makes a visitor's browser submit your form. Extensions such as Flask-WTF add a CSRF token to each form.
Step 7 · Know the limits of the debug server
Two things about this app are for development only.
The debugger runs any Python code you type into the traceback page in the browser. It is protected by the PIN in the server terminal, but anyone who reaches it can take over the machine. Never run --debug on a server, and never combine it with --host 0.0.0.0, which makes the server reachable from your whole network. The development server itself is also not built for real traffic. In production, run the app under a WSGI server such as Gunicorn behind Nginx, the same arrangement as in the Django deployment tutorial.
The entries are also kept only in memory. Stop the server with Ctrl+C and start it without debug mode, as a check:
uv run flask --app app runcurl -s http://127.0.0.1:5000/ | grep -o '<li>No entries yet.</li>'Check it worked
The server terminal shows Debug mode: off and a warning that this is a development server, with no debugger PIN. curl prints <li>No entries yet.</li>: the restart wiped every entry, which is why the next tutorial moves them into a database. If you run several server processes, each one would also keep its own separate list.
Stop the server with Ctrl+C in its terminal when you are done.
If you are not going on to the next tutorial, remove the demo project and the key:
cd ~
rm -rf ~/guestbook-demo
unset FLASK_SECRET_KEYNext steps
- Keep the entries in a database, split the app into a factory and a blueprint, and add tests: store data in a Flask app with SQLAlchemy.
- Compare with a framework that includes the database layer and an admin: create your first Django 6 app.
- Learn the testing tool most Python teams use: test Python code with pytest.
- See how a Python web app goes onto a server with Gunicorn and Nginx: deploy Django with Gunicorn and Nginx.
Related tutorials
- Store data in a Flask app with SQLAlchemy and an app factoryYou will build a Flask 3.1 guestbook that keeps its entries in a database through Flask-SQLAlchemy, organised with an application factory and a blueprint, and covered by pytest tests that run against a throwaway SQLite file.
- How to Create Your First Django 6 AppYou will create a Django 6.1 project with uv on Python 3.15, build a small bookmarks app with a database model, an admin screen, a page and a test, and see how the pieces connect.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials