Skip to content
Tutorials Center
My learning

Topics

Lesson 70 of 72 ยท Practice and Review

Practice Exercises with Solutions

14 hands-on Flask exercises with solutions on routing, templates, forms, sessions, cookies, databases, error handling, blueprints and JSON APIs. Run them in your browser.

Flask is learned by writing small apps, not by reading about them. This page gives you 14 exercises that cover the whole course, grouped by topic and roughly ordered from easy to harder. Each exercise has a short task, an editor with a working starter program, and a hidden solution.

You do not need a server. Every starter builds an app and talks to it through Flask's test client, then prints what came back, so you can compare your result with the expected output in the comments. Here is how to use the page:

  • Run the starter first. It already runs; the output just shows that your part is missing (usually a 404 or an empty result).
  • Write your part, then run again until the printed lines match the expected ones.
  • Open the solution last. Yours may differ and still be right. Compare ideas, not letters.

Exercises that need Flask begin with await micropip.install("flask"), which downloads Flask into the page the first time. Keep that line.

Routing and views

These practice routes and methods, URL converters, url_for and responses.

1. A friendly greeting (Beginner)

Add a route GET /hello/<name> that answers Hello, Mina! for /hello/mina: the name is capitalized and the status is 200.

Python Exercise 1: Greeting route

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
import micropip
await micropip.install("flask")

from flask import Flask

app = Flask(__name__)

@app.get("/hello/<name>")
def hello(name):
    return f"Hello, {name.capitalize()}!"

client = app.test_client()
response = client.get("/hello/mina")
print(response.status_code, response.get_data(as_text=True))

The <name> part of the URL becomes the name argument of the function. @app.get is a shortcut for @app.route(..., methods=["GET"]).

2. A tiny calculator (Beginner)

Add GET /add/<a>/<b> that returns JSON like {"sum": 5}. Only whole numbers should match, so /add/2/x must be a 404. A POST to the same URL must give 405.

Python Exercise 2: Add route

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
import micropip
await micropip.install("flask")

from flask import Flask

app = Flask(__name__)

@app.get("/add/<int:a>/<int:b>")
def add(a, b):
    return {"sum": a + b}

client = app.test_client()
ok = client.get("/add/2/3")
print(ok.status_code, ok.get_json())
print(client.get("/add/2/x").status_code)
print(client.post("/add/2/3").status_code)
print(client.get("/add/-4/10").get_json())

The int converter matches digits only, so x never reaches your function, and neither does -4: the converter does not accept signs unless you write <int(signed=True):a>. A route registered with @app.get answers other methods with 405 automatically.

3. Retire an old URL (Intermediate)

The page /old-home has moved to /new-home. Make /old-home redirect permanently (301) to the new page, and build the target with url_for instead of typing the path twice.

Python Exercise 3: Permanent redirect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
import micropip
await micropip.install("flask")

from flask import Flask, redirect, url_for

app = Flask(__name__)

@app.get("/new-home")
def new_home():
    return "This is the new home"

@app.get("/old-home")
def old_home():
    return redirect(url_for("new_home"), code=301)

client = app.test_client()
response = client.get("/old-home")
print(response.status_code, response.headers.get("Location"))
print(client.get("/old-home", follow_redirects=True).get_data(as_text=True))

url_for takes the function name (the endpoint), so if you later change the URL of new_home the redirect keeps working. 301 tells browsers and search engines the move is permanent.

Templates

These practice Jinja basics, control flow and filters.

4. A menu with an empty state (Beginner)

Write render_menu(items) using render_template_string. For a non-empty list it returns a <ul> with one numbered <li> per item (1. Soup); for an empty list it returns <p>Nothing today</p>. Jinja's autoescaping must neutralize HTML in the item names.

Python Exercise 4: Menu template

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
import micropip
await micropip.install("flask")

from flask import Flask, render_template_string

app = Flask(__name__)

MENU = (
    "{% if items %}<ul>"
    "{% for item in items %}<li>{{ loop.index }}. {{ item }}</li>{% endfor %}"
    "</ul>{% else %}<p>Nothing today</p>{% endif %}"
)

def render_menu(items):
    return render_template_string(MENU, items=items)

with app.app_context():
    print(render_menu(["Soup", "<b>Bread</b>"]))
    print(render_menu([]))

loop.index counts from 1. Autoescaping is on for render_template_string, so the <b> tags come out as harmless text. Never mark user data |safe just to make it look right.

5. A money filter (Intermediate)

Register a template filter named money that turns an integer number of cents into dollars with a thousands separator: 1250 becomes $12.50, 5 becomes $0.05.

Python Exercise 5: Custom filter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
import micropip
await micropip.install("flask")

from flask import Flask, render_template_string

app = Flask(__name__)

@app.template_filter("money")
def money(cents):
    return f"${cents / 100:,.2f}"

with app.app_context():
    for cents in [1250, 5, 123456789]:
        print(render_template_string("{{ value|money }}", value=cents))

@app.template_filter registers the function in the Jinja environment. Money is stored as integer cents elsewhere in this course; the filter converts only for display.

Forms, sessions and cookies

These practice forms, manual validation, cookies and sessions.

6. Validate a sign-up form (Intermediate)

POST /subscribe receives form fields name and email. The name needs at least 2 characters and the email must contain @ followed later by a dot. If everything is valid answer 201 with {"ok": true}. Otherwise answer 422 with {"errors": {...}} that has one entry per invalid field.

Python Exercise 6: Form validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
import micropip
await micropip.install("flask")

from flask import Flask, request

app = Flask(__name__)

@app.post("/subscribe")
def subscribe():
    name = request.form.get("name", "").strip()
    email = request.form.get("email", "").strip()
    errors = {}
    if len(name) < 2:
        errors["name"] = "Name must have at least 2 characters."
    local, at, domain = email.partition("@")
    if not (local and at and "." in domain):
        errors["email"] = "Enter a valid email address."
    if errors:
        return {"errors": errors}, 422
    return {"ok": True}, 201

client = app.test_client()
good = client.post("/subscribe", data={"name": "Mina", "email": "[email protected]"})
print(good.status_code, good.get_json())
bad = client.post("/subscribe", data={"name": "M", "email": "nope"})
print(bad.status_code, bad.get_json())

Collect every error before answering, so the user fixes all problems in one go. 422 Unprocessable Content is a common choice for "the request was well formed but the values are invalid".

7. Count visits with the session (Intermediate)

GET /visit should answer Visit number 1, then Visit number 2, and so on, counting per browser. A second client (another browser) starts again at 1. The app already has a secret key.

Python Exercise 7: Session counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
import micropip
await micropip.install("flask")

from flask import Flask, session

app = Flask(__name__)
app.config["SECRET_KEY"] = "dev-only"

@app.get("/visit")
def visit():
    session["visits"] = session.get("visits", 0) + 1
    return f"Visit number {session['visits']}"

first = app.test_client()
print([first.get("/visit").get_data(as_text=True) for _ in range(3)])
second = app.test_client()
print(second.get("/visit").get_data(as_text=True))

The count lives in a signed cookie, which the test client keeps per client object just as a browser does. Anyone can read that cookie, so never store secrets in it.

GET /theme/<name> accepts only light or dark (anything else is a 400), sets a theme cookie that lasts a year and is HttpOnly with SameSite=Lax, and answers Theme set to dark. GET / answers Current theme: dark, reading the cookie and defaulting to light.

Python Exercise 8: Theme cookie

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
import micropip
await micropip.install("flask")

from flask import Flask, abort, make_response, request

app = Flask(__name__)

@app.get("/theme/<name>")
def set_theme(name):
    if name not in {"light", "dark"}:
        abort(400)
    response = make_response(f"Theme set to {name}")
    response.set_cookie("theme", name, max_age=60 * 60 * 24 * 365,
                        httponly=True, samesite="Lax")
    return response

@app.get("/")
def home():
    return f"Current theme: {request.cookies.get('theme', 'light')}"

client = app.test_client()
print(client.get("/").get_data(as_text=True))
print(client.get("/theme/dark").get_data(as_text=True))
print(client.get("/").get_data(as_text=True))
print(client.get("/theme/purple").status_code)
print(client.get("/theme/light").headers["Set-Cookie"].split(";")[0])

Validate the value before storing it: a cookie is user input, and you will later echo it into pages.

Databases

These practice sqlite3 with Flask, Flask-SQLAlchemy and CRUD views.

9. A notes service with search (Intermediate)

POST /notes takes JSON {"text": "..."}, stores it and answers 201 with the new id; empty text is a 400. GET /notes?q=milk returns the texts that contain the search term (case-insensitive) as a JSON list, newest first. Use parameterized queries, so the search term ' OR 1=1 -- finds nothing instead of everything.

Python Exercise 9: Notes with sqlite3

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
import micropip
await micropip.install("flask")

import sqlite3
from flask import Flask, request

app = Flask(__name__)
db = sqlite3.connect(":memory:", check_same_thread=False)
db.execute("CREATE TABLE notes (id INTEGER PRIMARY KEY, text TEXT NOT NULL)")

@app.post("/notes")
def add_note():
    text = str((request.get_json(silent=True) or {}).get("text", "")).strip()
    if not text:
        return {"error": "text is required"}, 400
    cursor = db.execute("INSERT INTO notes (text) VALUES (?)", (text,))
    db.commit()
    return {"id": cursor.lastrowid}, 201

@app.get("/notes")
def search_notes():
    term = request.args.get("q", "")
    rows = db.execute(
        "SELECT text FROM notes WHERE text LIKE ? ORDER BY id DESC",
        (f"%{term}%",),
    ).fetchall()
    return [row[0] for row in rows]

client = app.test_client()
for text in ["Buy milk", "Call Dana", "Milk the plan for ideas"]:
    r = client.post("/notes", json={"text": text})
    print(r.status_code, r.get_json())
print(client.post("/notes", json={"text": "  "}).status_code)
print(client.get("/notes?q=milk").get_json())
print(client.get("/notes?q=' OR 1=1 --").get_json())

The ? placeholders send the value separately from the SQL, so quotes inside it are just characters. Building the query with an f-string would have been an SQL injection hole. SQLite's LIKE is case-insensitive for ASCII letters by default.

10. Toggle a task (Intermediate)

The starter defines a Task model with two rows. Add GET /tasks (a JSON list of {id, title, done}) and POST /tasks/<id>/toggle, which flips done and returns the task, or answers 404 for an unknown id.

Python Exercise 10: Flask-SQLAlchemy task toggle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
import micropip
await micropip.install(["flask", "flask-sqlalchemy"])

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import select
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

class Base(DeclarativeBase):
    pass

db = SQLAlchemy(model_class=Base)

class Task(db.Model):
    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str] = mapped_column(db.String(100))
    done: Mapped[bool] = mapped_column(default=False)

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"
db.init_app(app)

with app.app_context():
    db.create_all()
    db.session.add_all([Task(title="Write exercise"), Task(title="Review exercise")])
    db.session.commit()

def as_dict(task):
    return {"id": task.id, "title": task.title, "done": task.done}

@app.get("/tasks")
def list_tasks():
    tasks = db.session.scalars(select(Task).order_by(Task.id))
    return [as_dict(task) for task in tasks]

@app.post("/tasks/<int:task_id>/toggle")
def toggle_task(task_id):
    task = db.get_or_404(Task, task_id)
    task.done = not task.done
    db.session.commit()
    return as_dict(task)

client = app.test_client()
print(client.get("/tasks").get_json())
print(client.post("/tasks/1/toggle").get_json())
print(client.post("/tasks/1/toggle").get_json())
print(client.post("/tasks/99/toggle").status_code)

db.get_or_404 fetches by primary key and aborts with 404 when the row is missing. Changing the attribute is enough; commit() writes the change.

APIs, errors and structure

These practice JSON APIs, error handling, blueprints and authentication.

11. A small todo API (Intermediate)

Keep todos in a Python list. POST /api/todos with {"title": "..."} returns 201 and the new todo (id, title); a missing or blank title is a 400 with {"error": ...}. GET /api/todos/<id> returns the todo or a JSON 404 {"error": "not found"}. DELETE /api/todos/<id> returns an empty 204.

Python Exercise 11: Todo API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
import micropip
await micropip.install("flask")

from flask import Flask, request

app = Flask(__name__)
todos = []
next_id = 1

def find(todo_id):
    return next((todo for todo in todos if todo["id"] == todo_id), None)

@app.post("/api/todos")
def create_todo():
    global next_id
    title = str((request.get_json(silent=True) or {}).get("title", "")).strip()
    if not title:
        return {"error": "title is required"}, 400
    todo = {"id": next_id, "title": title}
    next_id += 1
    todos.append(todo)
    return todo, 201

@app.get("/api/todos/<int:todo_id>")
def read_todo(todo_id):
    todo = find(todo_id)
    if todo is None:
        return {"error": "not found"}, 404
    return todo

@app.delete("/api/todos/<int:todo_id>")
def delete_todo(todo_id):
    todo = find(todo_id)
    if todo is None:
        return {"error": "not found"}, 404
    todos.remove(todo)
    return "", 204

client = app.test_client()
created = client.post("/api/todos", json={"title": "Ship the exercise"})
print(created.status_code, created.get_json())
print(client.post("/api/todos", json={"title": " "}).get_json())
print(client.get("/api/todos/1").get_json())
print(client.delete("/api/todos/1").status_code)
print(client.get("/api/todos/1").status_code, client.get("/api/todos/1").get_json())

Ids are never reused because next_id only grows. A real app would let the database assign ids and handle concurrent requests.

12. JSON errors for the API only (Intermediate)

Register a 404 handler that returns JSON {"error": "not found"} for paths beginning with /api/ and a short HTML page (<h1>Page not found</h1>) for everything else. Both keep the 404 status.

Python Exercise 12: Error handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
import micropip
await micropip.install("flask")

from flask import Flask, request

app = Flask(__name__)

@app.get("/api/ping")
def ping():
    return {"pong": True}

@app.errorhandler(404)
def not_found(error):
    if request.path.startswith("/api/"):
        return {"error": "not found"}, 404
    return "<h1>Page not found</h1>", 404

client = app.test_client()
api = client.get("/api/missing")
print(api.status_code, api.content_type, api.get_json())
page = client.get("/missing")
print(page.status_code, page.content_type, page.get_data(as_text=True))

The handler receives the exception and must return a response with the status code, otherwise the browser would see a normal 200.

13. Protect an endpoint with an API key (Advanced)

Write a decorator require_api_key for views. A request without an X-API-Key header gets 401 and {"error": "missing key"}; a wrong key gets 403 and {"error": "invalid key"}; the correct key (s3cret) runs the view. Compare keys with secrets.compare_digest.

Python Exercise 13: API key decorator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
import micropip
await micropip.install("flask")

import secrets
from functools import wraps
from flask import Flask, request

app = Flask(__name__)
API_KEY = "s3cret"

def require_api_key(view):
    @wraps(view)
    def wrapper(*args, **kwargs):
        sent = request.headers.get("X-API-Key")
        if sent is None:
            return {"error": "missing key"}, 401
        if not secrets.compare_digest(sent.encode(), API_KEY.encode()):
            return {"error": "invalid key"}, 403
        return view(*args, **kwargs)
    return wrapper

@app.get("/api/report")
@require_api_key
def report():
    return {"report": "quarterly numbers"}

client = app.test_client()
for headers in [{}, {"X-API-Key": "guess"}, {"X-API-Key": "s3cret"}]:
    r = client.get("/api/report", headers=headers)
    print(r.status_code, r.get_json())

@wraps(view) keeps the original function name, which matters because Flask uses it as the endpoint name; without it every decorated view would be called wrapper and registering two would fail. compare_digest takes the same time however many leading characters match.

14. Group routes in a blueprint (Advanced)

Create a blueprint named shop mounted at /shop with two routes: / (the endpoint shop.index, answering Shop home) and /items/<int:item_id> (the endpoint shop.item, answering Item 3). Register it and print the URLs that url_for builds.

Python Exercise 14: Blueprint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solution
Python
import micropip
await micropip.install("flask")

from flask import Blueprint, Flask, url_for

app = Flask(__name__)

shop = Blueprint("shop", __name__, url_prefix="/shop")

@shop.get("/")
def index():
    return "Shop home"

@shop.get("/items/<int:item_id>")
def item(item_id):
    return f"Item {item_id}"

app.register_blueprint(shop)

with app.test_request_context():
    print(url_for("shop.index"), url_for("shop.item", item_id=3))

client = app.test_client()
print(client.get("/shop/").get_data(as_text=True))
print(client.get("/shop/items/3").get_data(as_text=True))
print(client.get("/items/3").status_code)

The blueprint name becomes the prefix of every endpoint (shop.index), so two blueprints can both have an index view without clashing. The url_prefix is added in front of each route's path.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A route is declared with @app.get("/add/<int:a>/<int:b>"). What does POST /add/2/3 return?

    The URL matches, but the route allows only GET (and HEAD, OPTIONS), so Flask answers 405 on its own.
  2. 2. Why should a custom decorator use functools.wraps?

    Without it every wrapped view is named wrapper, so url_for becomes confusing and registering two such views raises an endpoint conflict.
  3. 3. Which sqlite3 call is safe against SQL injection?

    Only the placeholder form sends the value separately from the SQL text. Changing the case of the string does not make concatenation safe.
  4. 4. In the theme-cookie exercise, why check that the name is light or dark before setting the cookie?

    Anything you store from the URL comes back later from the client. Restrict it to values you expect.

Summary

  • You practiced routes, converters and redirects; Jinja loops, escaping and filters; form validation, sessions and cookies; sqlite3 and Flask-SQLAlchemy; and JSON APIs, error handlers, decorators and blueprints.
  • The test client is the fastest way to try a Flask idea: build the app, call it, print the response.
  • When an exercise felt hard, reread the linked lesson, then solve it again from a blank editor a few days later.
  • Rewrite a solution a second way (a different converter, an error handler instead of an inline check) to deepen what you learned.

Next: Flask Interview Questions, common questions with concise answers to test how well you can explain what you know.