Start learning free

LESSON 103 OF 173 · BACKEND: PAYMENTS AND OTHER SERVICES

Call Another API in C#

Practice

A backend often needs data it doesn't keep itself. Your shop sells products, but the supplier makes them and runs its own API at http://127.0.0.1:8001, kept in SUPPLIER. To answer one request, your C# app can send a request of its own with await http.GetAsync(url), the same call your scripts used. On that trip, your shop is the client.

Here is the idea with another service, a weather API:

app.MapGet("/weather/{city}", async (string city) => {
    var response = await http.GetAsync(WEATHER + "/today/" + city);
    var data = await response.Content.ReadFromJsonAsync<JsonElement>();
    return Results.Json(new { city = city, temperature = data.GetProperty("temp") });
});

(int)response.StatusCode is the status the other API answered, ReadFromJsonAsync<JsonElement>() reads its JSON, and data.GetProperty("stock") picks one key out of it. The supplier answers GET /stock/{id} with JSON that has a "stock" key, and 404 for a product it doesn't sell. A 404 answer has no stock in it, so check the status before you read the stock, or your route throws and answers 500.

Your shop's own stock doesn't change. The new route reports the supplier's:

GET /products/1                 →  200  {"category": "kitchen", "id": 1, "name": "Mug", "price": 12, "stock": 10}
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 GET /products/{id}/supplier-stock with async (int id). Build the URL from SUPPLIER, "/stock/" and id, ask the supplier with http.GetAsync, and answer the product id with the supplier's stock. When the supplier answers 404, answer 404 with the error "The supplier doesn't sell this product".


Assignment
Follow the Coding Tutorial to add the supplier-stock route: build the URL, call the supplier, pass its stock on and handle its 404.


Hint
Joining id to text with + turns the number into text for you. Check (int)response.StatusCode right after the call, before you read the JSON.


STEP 1 OF 7
    Ctrl + Enter to check

    Svc Call Supplier 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