Start learning free

LESSON 104 OF 188 · BACKEND: PAYMENTS AND OTHER SERVICES

When the Other API Fails

Practice

Other services break: a bug, a full disk, a deploy gone wrong. The supplier then answers 500 Internal Server Error, with JSON like {"error": "The supplier is down"}. That JSON has no "stock", so your route crashes on data["stock"], and the customer gets your shop's own 500 error page, as if your shop were broken.

Check the status before you trust the answer. Your route is a gateway: a server that passes requests on to another server. When the server behind it fails, a gateway answers 502 Bad Gateway. Here is the idea in a weather app:

response = requests.get(WEATHER + "/today/" + name)
if response.status_code != 200:
    return jsonify({"error": "The weather service is not answering"}), 502
data = response.json()

502 tells the client that the problem is behind your shop: not in its request (a 4xx), and not a crash of your shop (a 500). Keep the 404 check first, so the Teapot still gets its 404; then "not 200" catches every other failure.

The check switches the supplier off for one request with POST /check/supplier-down, a page that only exists in the tests. Your shop must answer:

GET /products/1/supplier-stock  →  200  {"product_id": 1, "supplier_stock": 120}
POST /check/supplier-down {"times": 1}  →  200  {"down_next": 1}
GET /products/1/supplier-stock  →  502  {"error": "The supplier is not answering"}
GET /products/1/supplier-stock  →  200  {"product_id": 1, "supplier_stock": 120}
POST /check/supplier-down {"times": 1}  →  200  {"down_next": 1}
GET /products/3/supplier-stock  →  502  {"error": "The supplier is not answering"}
GET /products/6/supplier-stock  →  404  {"error": "The supplier doesn't sell this product"}

Your task: in supplier_stock, below the 404 check, answer "The supplier is not answering" with 502 whenever the supplier's status is not 200.


Assignment
Follow the Coding Tutorial to answer a clear 502 when the supplier fails, instead of crashing.


Hint
The new if goes between the 404 block and data = response.json(). Return the body and 502 together, like the 404 answer does.


STEP 1 OF 2
    Ctrl + Enter to check