Start learning free

LESSON 19 OF 188 · BACKEND: YOUR FIRST API

Two Filters at Once

Practice

A query string can carry several parameters, joined with &. In /products?category=office&max_price=5 the client asks for office products that cost 5 or less. The order of the parameters doesn't matter, because you read each one by its name.

Not every parameter is a number. A category is text, so you read it without type; like any parameter, it is None when the URL leaves it out. Here is the idea on another route, with two optional parameters:

@app.get("/greet")
def greet():
    name = request.args.get("name")
    times = request.args.get("times", type=int)
    if name is None:
        name = "friend"
    if times is None:
        times = 1
    return ("Hello, " + name + "! ") * times

To combine two filters, put one check inside the other: a product is added only when it passes the price check and the category check. Each check lets every product through when its parameter is None, so each filter also works alone. Your code must give:

GET /products?category=office                →  200  [{"id": 2, "name": "Notebook", …}, {"id": 4, "name": "Pen", …}]
GET /products?category=office&max_price=5    →  200  [{"id": 4, "name": "Pen", …}]
GET /products?max_price=20&category=kitchen  →  200  [{"id": 1, "name": "Mug", …}]
GET /products?category=garden                →  200  []
GET /products?category=home&max_price=10     →  200  []
GET /products?max_price=10                   →  200  [{"id": 2, "name": "Notebook", …}, {"id": 4, "name": "Pen", …}]
GET /products                                →  200  all 4 products

Your task: read a second query parameter, category, and change the loop in get_products so a product is added only when it passes both filters. Either filter can be left out.


Assignment
Follow the Coding Tutorial to read category and add the category check inside the price check.


Hint
The category check has the same shape as the price check: the None test first, then or, then a comparison with ==. The append line goes one level deeper, inside the new if.


STEP 1 OF 3
    Ctrl + Enter to check