Start learning free

LESSON 7 OF 173 · BACKEND: HOW THE WEB WORKS

An API Key in C#

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. In C#, you add the header to the client's DefaultRequestHeaders, with its name and its value, and every later request of that client carries it. For example, for a weather service that reads its key from X-Api-Key:

var weather = new HttpClient();
weather.DefaultRequestHeaders.Add("X-Api-Key", "my-weather-key");
var reply = await weather.GetAsync("https://weather.example/today");
Console.WriteLine((int)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 API_KEY. 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: ask for /stock without the key, read the JSON body, and print the status and the "error" from it. Then add the key in an X-Api-Key header, ask again, 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 API_KEY. With the key, the body is a JSON array: loop over data.EnumerateArray() and read each item's "id" and "stock" with GetProperty.


STEP 1 OF 8
    Ctrl + Enter to check

    Web Api Key in C#

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