Start learning free

LESSON 19 OF 173 · 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 each one is read by its name.

Not every parameter is a number. A category is text, so you use it as it is, with no int.TryParse; like any string? parameter, it is null when the URL leaves it out. In ASP.NET Core, each query parameter is one more parameter of the route's lambda, with the same name. Here is the idea on another route, with two optional parameters:

app.MapGet("/greet", (string? name, string? times) => {
    if (name == null) {
        name = "friend";
    }
    if (!int.TryParse(times, out var count)) {
        count = 1;
    }
    var text = "";
    for (var i = 0; i < count; i++) {
        text += "Hello, " + name + "! ";
    }
    return text;
});

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 missing, 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: the route's first line already has a second parameter, string? category. Change the loop in the /products route so a product is added only when it passes both filters. Either filter can be left out.


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


Hint
The category check has the same shape as the price check: the null test first, then ||, then a comparison with ==, with (string) before the dictionary's value. The Add line goes one level deeper, inside the new if.


STEP 1 OF 2
    Ctrl + Enter to check