Start learning free

LESSON 7 OF 173 · BACKEND: HOW THE WEB WORKS

An API Key in TypeScript

Practice

Some data is for everyone, and some only for customers. Anyone may read the supplier's prices, but its stock is only for the shops that buy from it. Ask for /stock without saying who you are, and the supplier answers 401 Unauthorized.

To know who is asking, many APIs give each customer an API key: a secret string sent with every request, in a header. You send it like any other header: after the address, pass an object whose headers key holds an object of them. For example, for a weather service that reads its key from X-Api-Key:

const reply = await fetch("https://weather.example/today", { headers: { "X-Api-Key": "my-weather-key" } });
console.log(reply.status);

A key works like a password: whoever has it can act as you. Keep it in your program, and never put it in a web page or a message. The starting code holds the shop's key in API_KEY, and the interface StockItem describes one item of the stock: an id and a stock, both numbers. Your script asks for the stock twice:

GET /stock                             →  401  Missing or wrong API key
GET /stock  (X-Api-Key: shop-key-123)  →  200  [{"id": 1, "stock": 120}, …]
Without the key: 401 Missing or wrong API key
With the key: 200
Product 1 has 120 in stock
Product 2 has 0 in stock
Product 3 has 8 in stock
Product 4 has 500 in stock
Product 5 has 0 in stock

Your task: inside main, ask for /stock without the key, and print the status and the error from the body. Then ask again with the key in an X-Api-Key header, print the status, and print the stock of each product.


Assignment
Follow the Coding Tutorial to ask for the supplier's stock, first without and then with the shop's API key.


Hint
The header's name is "X-Api-Key", in quotes because of its dashes, and its value is API_KEY. Declare response with let so you can reuse it. With the key, the body is an array of objects: read it with await response.json() into an array typed StockItem[], loop over it and read each item's id and stock.


STEP 1 OF 8
    Ctrl + Enter to check

    Web Api Key in TypeScript

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