Start learning free

LESSON 9 OF 188 · 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. A success and a refusal don't have the same keys, so check the status code before you read the body:

response = requests.post("https://api.example.com/signup", json={"email": ""})
if response.status_code == 400:
    print("Fix this:", response.json()["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: 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 response.json(), then use if response.status_code == 201: and an else. Read data["order_id"] only inside the if: a refusal has an "error" key instead.


STEP 1 OF 8
    Ctrl + Enter to check