Start learning free

LESSON 103 OF 188 · BACKEND: PAYMENTS AND OTHER SERVICES

Call Another API

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 Flask app can send a request of its own with requests.get(url), the same function your scripts used. On that trip, your shop is the client.

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

@app.get("/weather/<city>")
def weather(city):
    response = requests.get(WEATHER + "/today/" + city)
    data = response.json()
    return jsonify({"city": city, "temperature": data["temp"]})

response.status_code is the status the other API answered, and response.json() turns its JSON into a dictionary. 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 crashes with a 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/<int:product_id>/supplier-stock. Build the URL from SUPPLIER, "/stock/" and the product id, ask the supplier with requests.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".


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
product_id is an int, so turn it into text with str(product_id) before you join it to the URL. Check response.status_code right after the call, before you read the JSON.


STEP 1 OF 8
    Ctrl + Enter to check