Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Advanced Python

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Advanced Python

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.

The Flask core holds routing, templates, a development server and a test client. Extensions click on top: Flask-SQLAlchemy for the database, Flask-Login for users and Flask-Migrate for table changes. Flask core (the base plate) routing · Jinja2 templates · dev server · test client Flask-SQLAlchemy the database Flask-Login users Flask-Migrate table changes You choose each extension, so you own each choice
The core is small. A database layer, login, forms and migrations are extensions you add.

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. The for loop writes one list item per dish.
  • The else part 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 goes from the browser to the route table, which matches the menu rule, then to the menu view, then to the Jinja2 template, and the HTML comes back with status 200. GET /nope finds no rule and gets 404 without calling any view. Browser GET /menu Route table /menu matches menu() the view Jinja2 menu.html 200 HTML Browser GET /nope Route table no rule 404 Not Found no view is called
Every page in the blog follows the top path. A URL with no rule stops at the route table.

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_template looks in the templates folder 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

PieceJob
Flask(__name__)the application object; finds templates next to the file
@app.routewrites a rule into the route table
<name> in a ruletakes a value out of the URL and passes it to the view
render_template + Jinja2builds HTML; {{ }} prints and escapes, {% %} runs tags
app.test_client()sends requests straight into the app, no browser
WSGIhow 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 40 of 48

Previous
One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
Next post
Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode

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.

On this page

  • What "micro framework" means
  • The app object
  • Routes, views and a value in the URL
  • HTML with Jinja2
  • How one request travels
  • Checking it with the test client
  • WSGI: who actually calls your app
  • The development server
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.