Start learning free

LESSON 9 OF 173 · BACKEND: HOW THE WEB WORKS

When the Server Says No

Practice

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 three orders: a good one, one with a quantity of 0, and one with no quantity at all.

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.


STEP 1 OF 11
    Ctrl + Enter to check