🐍 Python for Everyone

← Back to the quiz

Chapter 22 Exercises 35 min, hands-on

Exercises: Building Web Apps & APIs — Flask & FastAPI

How to run these Download starter.py below, then run python3 starter.py from inside the folder you saved it in. Every task here is a plain Python function modeling exactly what a real Flask or FastAPI route function does with its inputs — no live server starts, and no real HTTP request is ever made.

1 Building a Flask template's context

Write build_task_lines(tasks) — return a list of "TITLE -- Pending/Done" strings, the same content a render_template() call would receive.

2 Reading a Flask query parameter

Write handle_search(simulated_args) — return a search message from a dict standing in for request.args.

3 Reading a Flask JSON body

Write handle_create_task(simulated_json_body) — return a created/error response from a dict standing in for request.json.

4 A FastAPI-style path parameter lookup

Write get_task(tasks, task_id) — look up a task by ID, the same job a type-hinted path parameter does.

5 A FastAPI-style query parameter filter

Write list_tasks(tasks, done=None) — filter tasks by a default-valued query parameter.

6 Pydantic-style validation

Write validate_task_shape(body) — check a dict's shape the way a Pydantic BaseModel would.

7 Comparing Flask vs. FastAPI defaults

Write default_response_shape(framework_name) — return each framework's typical response format.

8 Recognizing what React would need

Write is_consumable_by_a_frontend(response_body) — decide whether a response is JSON-shaped data or already-rendered HTML.

🐞 Task 9 — Debug the Code

This is supposed to look up a query parameter the way FastAPI would, returning a default value if the key is missing — but it crashes with a KeyError instead. Find and fix it.

buggy_get_query_param.py
def get_query_param(simulated_query_params, key, default=None):
    return simulated_query_params[key]


debug_params = {"limit": "10"}
print(get_query_param(debug_params, "limit"))
print(get_query_param(debug_params, "offset", default="0"))
← Back to Quiz Practice Bank →