A client can send anything: no name, a price written as text, a negative number. Never trust input. Before you store something, check it, and if it's wrong, answer 400 Bad Request with an error that tells the client what to fix. A 400 says the client made a mistake; a 500 says your server broke.
A map's get method gives null when a key is missing: data.get("color") is null when the body has no "color". To check that a value is a whole number, use value instanceof Integer. Here is the idea on another route:
@PostMapping("/ratings")
Object addRating(@RequestBody Map<String, Object> data) {
Object stars = data.get("stars");
if (!(stars instanceof Integer) || (int) stars < 1 || (int) stars > 5) {
return ResponseEntity.status(400).body(Map.of("error", "Stars must be a whole number from 1 to 5"));
}
return ResponseEntity.status(201).body(Map.of("stars", stars));
}
A return ends the method, so a refused product is never stored. Your code must give, in this order:
POST /products {"price": 5, "category": "home"} → 400 {"error": "Name is required"}
POST /products {"name": "", "price": 5, "category": "home"} → 400 {"error": "Name is required"}
POST /products {"name": "Cup", "category": "kitchen"} → 400 {"error": "Price must be a whole number of 0 or more"}
POST /products {"name": "Cup", "price": "5", "category": "kitchen"} → 400 the same price error
POST /products {"name": "Cup", "price": -1, "category": "kitchen"} → 400 the same price error
POST /products {"name": "Cup", "price": 4.5, "category": "kitchen"} → 400 the same price error
POST /products {"name": "Sticker", "price": 0, "category": "office"} → 201 {"id": 5, "name": "Sticker", "price": 0, "category": "office"}
GET /products/count → 200 {"count": 5}
Your task: in addProduct, read the name and the price with get, answer 400 with the right error when the name is missing or empty or the price isn't a whole number of 0 or more, and build the new product from the values you checked.
Assignment
Follow the Coding Tutorial to add the name check and the price check to addProduct.
Hint
Each check is an if with ||, and a return inside it. Put name == null before name.equals(""), and !(price instanceof Integer) before (int) price < 0, so neither runs on a value it can't handle. The newProduct line is missing at the start, so the file compiles only after the last step.
Free plan: 30 tutor messages. PRO is unlimited.
