Start learning free

LESSON 7 OF 173 · BACKEND: HOW THE WEB WORKS

An API Key

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. http.Get can't add a header, so you build the request with http.NewRequest, set the header with Header.Set, and send it with http.DefaultClient.Do. For example, for a weather service that reads its key from X-Api-Key:

request, _ := http.NewRequest("GET", "https://weather.example/today", nil)
request.Header.Set("X-Api-Key", "my-weather-key")
reply, _ := http.DefaultClient.Do(request)
fmt.Println(reply.StatusCode)

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 the constant apiKey. Your program 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: 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 and its value is apiKey. With the key, the body is a list of objects: decode it into a []map[string]any, loop over it with range, and read each item's "id" and "stock".


STEP 1 OF 10
    Ctrl + Enter to check