A server doesn't accept every request. When something is wrong in the request, like a missing field or a value that makes no sense, it answers with a status in the 400s, most often 400 Bad Request. The server works fine: sending the same request again gets the same answer.
A refusal still has a body, and many APIs put an error message in it that says what to fix. fetch doesn't throw an error on a 400: you get a normal response. A success and a refusal don't have the same keys, so check the status before you use the body:
const response = await fetch("https://api.example.com/signup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: "" }),
});
if (response.status === 400) {
const data = await response.json();
console.log("Fix this:", data.error);
}
Your script sends the supplier the three orders in orders: a good one, one with a quantity of 0, and one with no quantity at all. The interface Order writes quantity?, with a question mark, so TypeScript accepts an order without a quantity.
POST /orders {"product_id": 1, "quantity": 3} → 201 {"order_id": 1001, …}
POST /orders {"product_id": 1, "quantity": 0} → 400 {"error": "product_id and a quantity of 1 or more are required"}
POST /orders {"product_id": 2} → 400 {"error": "product_id and a quantity of 1 or more are required"}
It must print:
Status: 201 Order placed: 1001 Status: 400 Refused: product_id and a quantity of 1 or more are required Status: 400 Refused: product_id and a quantity of 1 or more are required
Your task: inside main, post each order in orders to /orders and print its status. Then print the order id if the status is 201, and the server's error message otherwise.
Assignment
Follow the Coding Tutorial to send the three orders and print what the supplier says about each one.
Hint
Read the body with await response.json(), then use if (response.status === 201) and an else. Read data.order_id only inside the if: a refusal has an error key instead, and a missing key gives undefined.
Free plan: 30 tutor messages. PRO is unlimited.
