Start learning free

LESSON 29 OF 173 · BACKEND: YOUR FIRST API

Search by Name

Practice

A search box sends what the user typed as a query parameter, often named q (for query): /products?q=no. The shop answers the products whose name contains that text, anywhere in the name.

In Java, contains checks whether one String is part of another. It is case-sensitive, so a capital letter doesn't match a small one. Turn both sides to lowercase with toLowerCase() and the case stops mattering:

String city = "Paris";
System.out.println(city.contains("ar"));                               // true
System.out.println(city.contains("PA"));                               // false: "PA" is not "Pa"
System.out.println(city.toLowerCase().contains("PA".toLowerCase()));  // true: "paris" contains "pa"

The search is a third optional filter in GET /products, next to max_price and category. getProducts already takes String q, which is null when the URL has no q. A product is added only when it passes all three filters, and sort still orders what is left. Finding nothing is not an error: the answer is an empty list. The lists below show product names only.

GET /products?q=no  →  200  [Notebook]
GET /products?q=NO  →  200  [Notebook]
GET /products?q=m  →  200  [Mug, Lamp]
GET /products?q=e&sort=price  →  200  [Pen, Notebook]
GET /products?q=p&category=office  →  200  [Pen]
GET /products?q=chair  →  200  []
GET /products  →  200  [Mug, Notebook, Lamp, Pen]

Your task: in getProducts, keep only the products whose name contains q, ignoring case.


Assignment
Follow the Coding Tutorial to add a search filter to GET /products.


Hint
Put the new if inside the category check, below name, and add the product to result inside it. When q is null, the check must let every product through.


STEP 1 OF 3
    Ctrl + Enter to check