A browser shows pages to people, but an API answers other programs: a phone app, a website's code, another server. Those programs may be written in any language, so they need the data as text, in a format they all read. That format is JSON.
In JSON, a list is written in [ ], and an object, like a Java Map, in { }, as pairs of a key and a value. Text goes in double quotes; numbers don't. In a @RestController, Spring turns what a route's method returns, a List or a Map, into a JSON response:
@GetMapping("/colors")
List<String> getColors() {
return List.of("red", "green", "blue");
}
This route answers the JSON list ["red", "green", "blue"], and tells the client the answer is JSON. When you run your code, you'll see the keys of each object in alphabetical order, so "category" comes first: a Map.of map doesn't keep the order you wrote. That's fine: programs find a value by its key, not by its place.
The products list is already in your file, filled in the constructor. Your app must answer:
GET /products → 200 [{"id": 1, "name": "Mug", "price": 12, "category": "kitchen"},
{"id": 2, "name": "Notebook", "price": 7, "category": "office"},
{"id": 3, "name": "Lamp", "price": 29, "category": "home"},
{"id": 4, "name": "Pen", "price": 2, "category": "office"}]
GET / → 200 Welcome to the shop!
Your task: add a route for /products with a method named getProducts that returns the whole products list, which Spring sends as JSON.
Assignment
Follow the Coding Tutorial to add the GET /products route and send the product list as JSON.
Hint
Copy the shape of the home route: the @GetMapping annotation with the new path, then the method. Its return type is the type of the products field, List<Map<String, Object>>, and it returns the field itself.
Free plan: 30 tutor messages. PRO is unlimited.
