A shop can't write a route for each of its products. Instead, one route has a placeholder in its path: a path variable, written in curly braces. In /products/{productId}, the placeholder matches whatever is written in that place, so /products/3 matches with productId equal to 3. Spring passes the value to your method's parameter marked @PathVariable, which has the same name.
The parameter's type does the converting: with int productId, Spring turns the text from the path into a whole number. A path like /products/mug fits the placeholder, but "mug" can't become an int, so Spring answers 400 Bad Request without calling your method. /products/count still goes to its own route: a path with fixed text beats a placeholder. Here is the same idea on another route:
@GetMapping("/square/{number}")
Map<String, Object> square(@PathVariable int number) {
return Map.of("square", number * number);
}
Once you have the id, find the product with a for-each loop: check each product's "id", and when it equals productId, return that product. return ends the method, so the loop stops there. A map gives its values back as Object, so cast the id with (int) before comparing. Java also wants a return for when no product matches: after the loop, return ResponseEntity.status(404).build(), an empty answer with status 404. The method returns Object, so it can give back either one.
Your app must answer:
GET /products/1 → 200 {"id": 1, "name": "Mug", "price": 12, "category": "kitchen"}
GET /products/3 → 200 {"id": 3, "name": "Lamp", "price": 29, "category": "home"}
GET /products/4 → 200 {"id": 4, "name": "Pen", "price": 2, "category": "office"}
GET /products/count → 200 {"count": 4}
GET /products/mug → 400 (an HTML error page)
Your task: add a route for /products/{productId} with a method named getProduct that returns Object and takes @PathVariable int productId. It loops over products and returns the product whose "id" equals productId; after the loop, it answers 404.
Assignment
Follow the Coding Tutorial to add the route that answers one product by its id.
Hint
The name inside the curly braces and the parameter's name must be the same, productId. Inside the loop, compare (int) product.get("id") with productId using ==. ResponseEntity and PathVariable are already imported.
Free plan: 30 tutor messages. PRO is unlimited.
