Start learning free

LESSON 70 OF 173 · 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 handler saves it with an INSERT statement.

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

res, _ := db.Exec("INSERT INTO subscribers (email) VALUES (?)", "sam@example.com")
id, _ := res.LastInsertId()
fmt.Println(id)   // 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 res.LastInsertId() tells you which. And db.Exec outside a transaction saves the row in shop.db right away, so every connection sees it.

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 a handler for POST /products. Decode the body into a Product, insert the name, the price and the category (which may be missing) with ? placeholders, and answer the new id with the status 201.


Assignment
Follow the Coding Tutorial to add the POST /products handler, which saves a new product in the database.


Hint
Category is a *string: when the Candle sends none, it stays nil, and nil is stored as NULL. LastInsertId gives an int64, so the answer's map holds int64 values.


STEP 1 OF 7
    Ctrl + Enter to check