Start learning free

LESSON 26 OF 188 · BACKEND: YOUR FIRST API

One Way to Send Errors in Python

Practice

Your shop sends errors from six places, and each one builds {"error": ...} by hand. A client relies on every error having the same shape: it reads the message under the key "error". One typo in one place, like "eror", and the client loses that message.

The fix is a helper function: an ordinary function, with no decorator, that builds the answer in one place. It isn't a route; the routes call it and return what it gives them. A function can return two values, a body and a status, and the route passes both on to Flask. A helper for success answers could look like this (not part of the shop):

def created(item):
    return jsonify(item), 201

@app.post("/notes")
def add_note():
    note = request.get_json()
    notes.append(note)
    return created(note)

The answers stay exactly the same; only the code gets tidier. The requests and answers your code must give, in this order:

GET /products/9  →  404  {"error": "Product not found"}
POST /products  {"price": 5, "category": "kitchen"}
  →  400  {"error": "Name is required"}
POST /products  {"name": "Cup", "price": -1, "category": "kitchen"}
  →  400  {"error": "Price must be a whole number of 0 or more"}
DELETE /products/9  →  404  {"error": "Product not found"}
PUT /products/9  {"name": "Cup", "price": 5, "category": "kitchen"}
  →  404  {"error": "Product not found"}
PATCH /products/9  {"price": 5}  →  404  {"error": "Product not found"}
POST /products  {"name": "Cup", "price": 5, "category": "kitchen"}
  →  201  {"id": 5, "name": "Cup", "price": 5, "category": "kitchen"}
GET /products/5  →  200  {"id": 5, "name": "Cup", "price": 5, "category": "kitchen"}

Your task: write error_response(message, status), which returns the JSON body {"error": message} with the given status, and use it for every error answer in the shop: the 404 of get_product, delete_product, update_product and patch_product, and the two 400s of add_product.


Assignment
Follow the Coding Tutorial to write the error_response helper and send every error through it.


Hint
The helper goes under shop, outside every route. In each route, write return error_response(...): without return, the helper's answer is never sent.


STEP 1 OF 8
    Ctrl + Enter to check

    Shop Error Helper in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free