Start learning free

LESSON 103 OF 173 · BACKEND: PAYMENTS AND OTHER SERVICES

Call Another API in JavaScript

Practice

Your shop doesn't make what it sells: it buys from a supplier, and the supplier has its own API, at the address stored in SUPPLIER. To tell a customer how many of a product the supplier still has, a route of your shop asks the supplier first. While it handles one request, your shop sends one of its own: it is now the client of another API.

The tool is the one your scripts used, fetch(url). Here it is inside a route of a weather app, which asks a weather service:

app.get("/cities/:name/weather", async (req, res) => {
  const url = WEATHER + "/today/" + req.params.name;
  const response = await fetch(url);
  const data = await response.json();
  res.json({ city: req.params.name, temperature: data.temp });
});

Three details matter. fetch and .json() both wait for the network, so each needs await, and the route's function must be async. The id in the path is text, so Number(...) turns it into the number your answer shows. And look at response.status before you use the answer: when the other API says 404, its JSON doesn't have the key you want, and res.json quietly leaves out a key whose value is undefined.

The supplier answers GET /stock/<id> with JSON like {"id": 1, "stock": 120}, and it doesn't sell the Teapot (id 6). Your shop must answer:

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 the route GET /products/:productId/supplier-stock. It asks the supplier for /stock/<id>, answers 404 with an error when the supplier doesn't sell the product, and otherwise passes the supplier's stock on as supplier_stock.


Assignment
Follow the Coding Tutorial to build the route that asks the supplier how many of a product it still has.


Hint
Build the address with SUPPLIER + "/stock/" + productId. Check response.status right after the fetch, before you read data.stock.


STEP 1 OF 8
    Ctrl + Enter to check

    Svc Call Supplier in JavaScript

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