Start learning free

LESSON 103 OF 173 · BACKEND: PAYMENTS AND OTHER SERVICES

Call Another API in Go

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 the constant supplier. To answer one request, your Go server can send a request of its own with http.Get(url), the same function your first Go requests used. On that trip, your shop is the client.

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

app.HandleFunc("GET /weather/{city}", func(w http.ResponseWriter, r *http.Request) {
	city := r.PathValue("city")
	response, _ := http.Get(weather + "/today/" + city)
	defer response.Body.Close()
	var data map[string]int
	json.NewDecoder(response.Body).Decode(&data)
	writeJSON(w, 200, map[string]any{"city": city, "temperature": data["temp"]})
})

response.StatusCode is the status the other API answered, defer response.Body.Close() closes its body when the handler ends, and json.NewDecoder(response.Body).Decode(&data) turns its JSON into a map. 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, and in Go a missing map key reads as 0. So check the status before you read the stock, or your handler answers a false stock of 0.

Your shop's own stock doesn't change. The new handler 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 a handler for "GET /products/{id}/supplier-stock". Turn the id into a number, build the URL from supplier, "/stock/" and the id, ask the supplier with http.Get, 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" and stop the handler with return.


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


Hint
id is an int, so turn it into text with strconv.Itoa(id) before you join it to the URL. Check response.StatusCode right below the defer line, before you decode the JSON.


STEP 1 OF 9
    Ctrl + Enter to check

    Svc Call Supplier in Go

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