Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
A one-file Flask app with three routes and one Jinja2 template. What each line does, how a request finds its view, what a 404 looks like, and how a WSGI server calls your app.
What you will learn
- Explain what a micro framework is and what Flask leaves to extensions
- Register routes with @app.route, including a value in the URL
- Render HTML with a Jinja2 template and render_template
- Check an app with the test client and call it by hand as a WSGI app
Before you start
- Python functions and decorators
- Basic HTML
Think about a box of LEGO bricks. You don't get a finished model. You get a small base plate and a few bricks, and you click on the pieces you need. The same box can build a car or a house, and any piece you don't need stays in the box.
That's Flask. It gives you a small base, and you add the parts your app needs. In this article we build one small app file with three routes and one template, and we look at what each line does. Once you know the pieces, it gets much easier to review a Flask app that an AI tool wrote for you.
What "micro framework" means
People call Flask a micro framework. Micro doesn't mean it's only for tiny apps. It means the core is small. The project's requirements.txt has one line:
Flask==3.1.3
Ask for the version and Werkzeug shows up under it:
python -m flask --version
Python 3.12.14
Flask 3.1.3
Werkzeug 3.1.9
Werkzeug is the library Flask is built on. It handles requests and responses. Jinja2, the template engine, comes in with Flask too.
So the core gives you routing, templates, a development server and a test client. It doesn't give you a database layer, login, forms or migrations. For those you add extensions, like Flask-SQLAlchemy, Flask-Login and Flask-Migrate. Nothing is picked for you.
What do people build with it? Websites with pages, and full monolithic apps like the blog in this course, where one Flask app serves every page. Small APIs that return JSON. Webhook receivers. You can serve a machine learning model with Flask too, but in this course the AI services use FastAPI (see FastAPI hello world), so here Flask is all about the web app.
The app object
A whole Flask app can fit in one file. It starts with two lines:
from flask import Flask
app = Flask(__name__)
__name__ tells Flask where this file sits, so it can find the templates folder next to it. The app object is your application. Every route, every setting and every request goes through it.
With only these two lines, ask Flask for its routes:
Endpoint Methods Rule
-------- ------- -----------------------
static GET /static/<path:filename>
There's already one. Flask adds static on its own, for files like CSS and images. Everything else, we add.
Routes, views and a value in the URL
Here is the finished app.py:
from flask import Flask, render_template
app = Flask(__name__)
DISHES = [
{"name": "Pasta", "price": "9.50"},
{"name": "Soup", "price": "4.00"},
]
@app.route("/")
def home():
return "Hello from Flask"
@app.route("/hello/<name>")
def hello(name):
return f"Hello, {name}"
@app.route("/menu")
def menu():
return render_template(
"menu.html", dishes=DISHES, title="Menu"
)
@app.route("/") is a decorator. It registers the function below it for that URL. A function like home is called a view, and Flask turns the string it returns into a response.
The decorator doesn't run your function. It writes a row in the route table, and Flask looks the row up when a request comes in. python -m flask --app app routes now shows four rows:
Endpoint Methods Rule
-------- ------- -----------------------
hello GET /hello/<name>
home GET /
menu GET /menu
static GET /static/<path:filename>
The endpoint name is simply the function name.
Look at /hello/<name>. The part in angle brackets is a variable. A request for /hello/Sam matches the rule, Flask takes Sam out of the URL and passes it to the function as name, and the view returns Hello, Sam. One route answers many URLs, and the URL itself becomes the input.
HTML with Jinja2
Plain text is fine for a start, but a page needs HTML. The menu view calls render_template with menu.html and two values. Flask looks for that file in the templates folder:
<h1>Today's {{ title }}</h1>
<ul>
{% for dish in dishes %}
<li>{{ dish.name }}: {{ dish.price }}</li>
{% else %}
<li>Nothing today</li>
{% endfor %}
</ul>
- Double curly braces print a value, so the heading reads Today's Menu.
{% ... %}is a tag. Theforloop writes one list item per dish.- The
elsepart only shows when the list is empty, so the page would say Nothing today instead of showing an empty list. - Values printed with
{{ }}are escaped, so text typed by a user can't slip its own HTML into your page.
How one request travels
GET /menu reaches the app, Flask checks the route table, and /menu matches the menu rule. Flask calls the view, the view hands the dishes to the template, Jinja2 builds the HTML, and the HTML goes back with status 200. When no rule matches, like /nope, Flask sends back 404 Not Found without calling any view.
Checking it with the test client
You don't need a browser to try this. app.test_client() gives you a client that sends requests straight into the app. Here is the first part of check_app.py:
from app import app
client = app.test_client()
for url in ["/", "/hello/Sam", "/menu", "/nope"]:
resp = client.get(url)
print("GET", url, "->", resp.status_code)
print(resp.get_data(as_text=True))
print(app.url_map)
GET / -> 200
Hello from Flask
GET /hello/Sam -> 200
Hello, Sam
GET /menu -> 200
<h1>Today's Menu</h1>
<ul>
<li>Pasta: 9.50</li>
<li>Soup: 4.00</li>
</ul>
GET /nope -> 404
<!doctype html>
<html lang=en>
<title>404 Not Found</title>
<h1>Not Found</h1>
<p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>
Map([<Rule '/static/<filename>' (GET, HEAD, OPTIONS) -> static>,
<Rule '/' (GET, HEAD, OPTIONS) -> home>,
<Rule '/hello/<name>' (GET, HEAD, OPTIONS) -> hello>,
<Rule '/menu' (GET, HEAD, OPTIONS) -> menu>])
Every rule allows GET, and Flask added HEAD and OPTIONS on its own. This same test client is what pytest uses to test a Flask app, as you'll see in Testing the Flask blog with pytest.
WSGI: who actually calls your app
A web server calls your app through a standard called WSGI, the Web Server Gateway Interface. The server reads the request and puts its details (the method, the path, the server name) in a dictionary called environ. Then it calls the app like a function, with environ and a function called start_response. The app sends the status back through start_response and returns the body.
The bottom of check_app.py does exactly that by hand:
# The app is a WSGI callable: call it by hand.
environ = {
"REQUEST_METHOD": "GET",
"PATH_INFO": "/hello/WSGI",
"SERVER_NAME": "localhost",
"SERVER_PORT": "80",
"wsgi.url_scheme": "http",
"wsgi.input": None,
"wsgi.errors": None,
}
def start_response(status, headers):
print("status:", status)
body = app(environ, start_response)
print("body:", b"".join(body).decode())
status: 200 OK
body: Hello, WSGI
So any server that speaks WSGI can run any Flask app. Your views stay plain Python functions, and the server takes care of the network.
The development server
For your own machine, Flask comes with a development server from Werkzeug:
python -m flask --app app run
* Serving Flask app 'app'
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5055
Press CTRL+C to quit
127.0.0.1 - - [time] "GET /hello/Sam HTTP/1.1" 200 -
127.0.0.1 - - [time] "GET /menu HTTP/1.1" 200 -
Take the warning at its word. This server is for your machine while you work. When an app goes out to users, a production WSGI server such as Gunicorn runs it instead. 127.0.0.1 is your own computer, and each request shows up as one log line with its status.
Common mistakes
- Thinking the decorator calls the view. It only registers a rule. The view runs when a matching request arrives.
- Putting templates in the wrong place.
render_templatelooks in thetemplatesfolder next to the app file. - Shipping the development server. It prints its own warning. Use a production WSGI server for real users.
- Expecting Flask to bring a database or login. Those are extensions you pick and add.
Quick recap
| Piece | Job |
|---|---|
Flask(__name__) | the application object; finds templates next to the file |
@app.route | writes a rule into the route table |
<name> in a rule | takes a value out of the URL and passes it to the view |
render_template + Jinja2 | builds HTML; {{ }} prints and escapes, {% %} runs tags |
app.test_client() | sends requests straight into the app, no browser |
| WSGI | how a server calls the app: app(environ, start_response) |
Try it yourself
Add an /about route that returns one sentence, add it to the loop in check_app.py and run the script again. Or prompt an AI tool to add it, then read every line it gives you. Next, set up a real project with uv in Your first Flask app with uv.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
A regex is a stencil for a shape of text. Watch it slide and back up, build patterns with \d, \w, quantifiers and anchors, use search, findall, sub and split, pull parts out with named groups, and test AI-written patterns on edge cases.
Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
A test is a line on a checklist your code must pass every time. Catch a discount bug with assert, read the E lines in the pytest report, cover cases with parametrize, share a cart with a fixture, test errors with pytest.raises, and see why a passing test from an AI tool can prove nothing.
Async Python: async def, await, asyncio.gather and the Blocking Trap
One cook, several pots: async lets one program wait on many things at once. See what async def and await really do, why three awaits in a row are no faster, how gather and TaskGroup bring 0.6 seconds down to 0.2, and the two mistakes that catch almost everyone.
Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.
