Start learning free

LESSON 4 OF 173 · BACKEND: HOW THE WEB WORKS

Check the Status First

Practice

Every answer from a server starts with a status code: a number that says how the request went. 200 OK means the body holds what you asked for. 404 Not Found means there is nothing at that address. A 404 is not a crash: the request went out, and the server answered.

The status tells you what the body holds, so check it before you use the body. In C#, response.StatusCode names the status, and (int)response.StatusCode gives its number. Here is the idea on another page of the supplier:

var response = await http.GetAsync(SUPPLIER + "/catalog?page=1");
if ((int)response.StatusCode == 200) {
    Console.WriteLine("Got the page");
}

Your script looks up three product ids: 3, 99 and 5. The supplier has no product 99, so it answers 404, and its body holds an error instead of a product. Reading GetProperty("name") from that body would stop the script with a KeyNotFoundException.

GET /prices/3   →  200  {"name": "Lamp", "price": 14, …}
GET /prices/99  →  404  {"error": "No product with that id"}
GET /prices/5   →  200  {"name": "Plant", "price": 6, …}

Your script must print:

Product 3 - status 200
Lamp costs 14
Product 99 - status 404
No such product at the supplier
Product 5 - status 200
Plant costs 6

Your task: loop over productIds, get /prices/ followed by each id, and print the id and its status code. For a 200, print the product's name, " costs " and its price. For a 404, print "No such product at the supplier".


Assignment
Follow the Coding Tutorial to request each product, print its status code and handle the 200 and 404 answers.


Hint
+ turns the id into text by itself, so SUPPLIER + "/prices/" + productId is a whole address. Print the status before the if, and start the else if line with the if's closing }.


STEP 1 OF 8
    Ctrl + Enter to check