Start learning free

LESSON 70 OF 188 · BACKEND: APIS WITH A DATABASE

Add a Product (INSERT)

Practice

Your shop reads its products from shop.db. Now clients can add one: they send a POST to /products, the same path as the list, with the new product in the JSON body. Your route saves it with an INSERT statement.

Here is an INSERT on another table, a list of newsletter subscribers:

cursor = db.execute("INSERT INTO subscribers (email) VALUES (?)", ("sam@example.com",))
db.commit()
print(cursor.lastrowid)   # the id the database chose for the new row

Three things matter. Each ? takes one value, in order, so whatever text the client sends stays a value and never becomes SQL. You leave the id out: the database picks the next free number, and cursor.lastrowid tells you which. And db.commit() saves the change for good: before it, only your own connection sees the new row.

Starting from the shop's 8 products, your code must answer:

POST /products  {"name": "Vase", "price": 18, "category": "home"}  →  201  {"id": 9}
GET /products/9  →  200  {"id": 9, "name": "Vase", "price": 18, "category": "home", "stock": 0}
POST /products  {"name": "Candle", "price": 6}  →  201  {"id": 10}
GET /products?max_price=6  →  200  [{"id": 4, "name": "Pen", …}, {"id": 10, "name": "Candle", "price": 6, "category": null, "stock": 0}]

Your task: add the route POST /products. Read the body, insert the name, the price and the category (which may be missing) with ? placeholders, commit, and answer the new id with the status 201.


Assignment
Follow the Coding Tutorial to add the add_product route, which saves a new product in the database.


Hint
Read the category with data.get("category"): the Candle has none, and None is stored as NULL. Don't forget db.commit() before you answer.


STEP 1 OF 7
    Ctrl + Enter to check