Start learning free

LESSON 20 OF 173 · BACKEND: YOUR FIRST API

Add a Product

Practice

Until now every handler used GET, the method for reading. To send new data, a client uses POST. A pattern names the method and the path together, so "GET /products" and "POST /products" can go to two different handlers.

A POST carries a request body, usually a JSON object. json.NewDecoder(r.Body).Decode(&data) reads it into the variable data, filling the fields whose JSON names match. When something new is stored, the answer has the status 201 Created: you pass 201 to writeJSON, just like the 404. Here is the idea on another route:

type Message struct {
	Text string `json:"text"`
}

var messages = []string{}

app.HandleFunc("POST /messages", func(w http.ResponseWriter, r *http.Request) {
	var data Message
	json.NewDecoder(r.Body).Decode(&data)
	messages = append(messages, data.Text)
	writeJSON(w, 201, map[string]int{"count": len(messages)})
})

The client doesn't choose the id: the shop gives the new product the largest id so far, plus 1, and appends it to products, so every handler sees it. Your code must give, in this order:

POST /products  {"name": "Plant", "price": 15, "category": "home"}  →  201  {"id": 5, "name": "Plant", "price": 15, "category": "home"}
POST /products  {"name": "Stapler", "price": 9, "category": "office"}  →  201  {"id": 6, "name": "Stapler", "price": 9, "category": "office"}
GET /products/6  →  200  {"id": 6, "name": "Stapler", …}
GET /products?category=office  →  200  [{"id": 2, …}, {"id": 4, …}, {"id": 6, …}]
GET /products/count  →  200  {"count": 6}

Your task: add a POST /products handler that decodes the JSON body into a Product, gives the new product the next id, appends it to products and answers it with the status 201.


Assignment
Follow the Coding Tutorial to build the POST handler, from the pattern to the 201 answer.


Hint
Find the largest id with a variable that starts at 0 and a loop that keeps the biggest ID it has seen. Build the new product in newProduct, not product, and answer it with writeJSON and the status 201.


STEP 1 OF 9
    Ctrl + Enter to check