A client often wants only part of the data, and it can say so in the URL. Everything after the ? is the query string, made of name=value pairs. In /products?max_price=10 the path is still /products, so the same route answers: max_price is the name and 10 is the value.
In Flask you read a query parameter with request.args.get. Everything in a URL is text, so add type=int when you want a whole number. When the parameter is missing, or isn't a whole number, you get None. Here is the idea on another route:
@app.get("/double")
def double():
number = request.args.get("number", type=int)
if number is None:
return "Send a whole number, like /double?number=4"
return str(number * 2)
The filter is a loop you already know: start an empty list, go through the products, and append the ones that pass the check. When there is no max_price, every product passes, so /products still answers the whole list. Your code must give:
GET /products?max_price=10 → 200 [{"id": 2, "name": "Notebook", …}, {"id": 4, "name": "Pen", …}]
GET /products?max_price=12 → 200 [{"id": 1, "name": "Mug", …}, {"id": 2, …}, {"id": 4, …}]
GET /products?max_price=1 → 200 []
GET /products → 200 all 4 products
GET /products?max_price=cheap → 200 all 4 products
GET /products/3 → 200 {"id": 3, "name": "Lamp", "price": 29, "category": "home"}
Your task: change get_products so it reads max_price from the query string and answers only the products that cost max_price or less, or every product when there is no limit.
Assignment
Follow the Coding Tutorial to read max_price and filter the list in get_products.
Hint
Check max_price is None first, then or, then compare the price with <=. Return result after the loop, not inside it.
Free plan: 30 tutor messages. PRO is unlimited.
