A backend often needs data it doesn't keep itself. Your shop sells products, but the supplier makes them and runs its own API at http://127.0.0.1:8001, kept in SUPPLIER. To answer one request, your Spring app can send a request of its own with client, the HttpClient already in the controller, the same kind your programs used. On that trip, your shop is the client.
Here is the idea with another service, a weather API:
@GetMapping("/weather/{city}")
Object weather(@PathVariable String city) throws Exception {
HttpRequest request = HttpRequest.newBuilder(URI.create(WEATHER + "/today/" + city)).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
Map<String, Object> data = new ObjectMapper().readValue(response.body(), Map.class);
return Map.of("city", city, "temperature", data.get("temp"));
}
response.statusCode() is the status the other API answered, and readValue turns the JSON text of response.body() into a map. The supplier answers GET /stock/{id} with JSON that has a "stock" key, and 404 for a product it doesn't sell. A 404 answer has no stock in it, so check the status before you read the stock, or your route crashes with a 500.
Your shop's own stock doesn't change. The new route reports the supplier's:
GET /products/1 → 200 {"category": "kitchen", "id": 1, "name": "Mug", "price": 12, "stock": 10}
GET /products/1/supplier-stock → 200 {"product_id": 1, "supplier_stock": 120}
GET /products/2/supplier-stock → 200 {"product_id": 2, "supplier_stock": 0}
GET /products/4/supplier-stock → 200 {"product_id": 4, "supplier_stock": 500}
GET /products/6/supplier-stock → 404 {"error": "The supplier doesn't sell this product"}
Your task: add GET /products/{productId}/supplier-stock with the method supplierStock. Build the URL from SUPPLIER, "/stock/" and the product id, ask the supplier with client.send, and answer the product id with the supplier's stock. When the supplier answers 404, answer 404 with the error "The supplier doesn't sell this product".
Assignment
Follow the Coding Tutorial to add the supplier-stock route: build the URL and the request, call the supplier, pass its stock on and handle its 404.
Hint
Joining a String and an int with + gives text, so productId needs no conversion. Check response.statusCode() right after the call, before you read the JSON.
Free plan: 30 tutor messages. PRO is unlimited.
