Start learning free

LESSON 18 OF 173 · BACKEND: YOUR FIRST API

Filter with a Query String in Java

Practice

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 Spring you read a query parameter by adding it to the method's parameters, marked @RequestParam. Give it the type you want: Spring turns the URL's text into an Integer for you, and answers 400 Bad Request on its own when the text isn't a whole number. With required = false the parameter can be left out, and then it is null: that's why its type is Integer, which can be null, and not int. Here is the idea on another route:

@GetMapping("/double")
String doubleIt(@RequestParam(required = false) Integer number) {
    if (number == null) {
        return "Send a whole number, like /double?number=4";
    }
    return String.valueOf(number * 2);
}

The filter is a loop you already know: start an empty list, go through the products, and add 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  →  400  (an HTML error page)
GET /products/3                →  200  {"id": 3, "name": "Lamp", "price": 29, "category": "home"}

Your task: change getProducts so it takes max_price from the query string and returns only the products that cost max_price or less, or every product when there is no limit.


Assignment
Follow the Coding Tutorial to take max_price and filter the list in getProducts.


Hint
Check max_price == null first, then ||, then compare the price with <=. A value from the map is an Object, so write (int) before product.get("price"). Return result after the loop, not inside it.


STEP 1 OF 6
    Ctrl + Enter to check

    Shop Max Price in Java

    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free