Start learning free

LESSON 14 OF 173 · BACKEND: YOUR FIRST API

Send JSON

Practice

A browser shows pages to people, but an API answers other programs: a phone app, a website's code, another server. Those programs may be written in any language, so they need the data as text, in a format they all read. That format is JSON.

In JSON, a list is written in [ ], and an object in { }, as pairs of a key and a value. Text goes in double quotes; numbers don't. Your file already has a helper, writeJSON(w, status, v): it labels the answer as JSON, writes the status, and turns the Go value v into JSON. A slice becomes a JSON list:

app.HandleFunc("GET /colors", func(w http.ResponseWriter, r *http.Request) {
	colors := []string{"red", "green", "blue"}
	writeJSON(w, 200, colors)
})

This handler answers the JSON list ["red", "green", "blue"], and tells the client the answer is JSON. A struct becomes a JSON object. The tags in the Product struct, like `json:"name"`, name its keys: the field Name becomes the key "name".

The products slice is already in your file. Your app must answer:

GET /products  →  200  [{"id": 1, "name": "Mug", "price": 12, "category": "kitchen"},
                        {"id": 2, "name": "Notebook", "price": 7, "category": "office"},
                        {"id": 3, "name": "Lamp", "price": 29, "category": "home"},
                        {"id": 4, "name": "Pen", "price": 2, "category": "office"}]
GET /          →  200  Welcome to the shop!

Your task: register a handler for "GET /products" that answers the whole products slice as JSON with status 200, using writeJSON.


Assignment
Follow the Coding Tutorial to add the GET /products handler and send the product list as JSON.


Hint
Copy the shape of the handler for "GET /{$}", with the new pattern. Inside it, call writeJSON with w, the status and the slice.


STEP 1 OF 2
    Ctrl + Enter to check