45. Building a JSON API — Homework solutions
The solutions are in exercises/45/homework/solutions/.
Problems 1 and 2 are single files, run from go-work.
Problem 3 and the challenge are folders: cd into the
folder, then use go run . or go test -v.
Problem 1 — A quotes API
Problem. Serve a fixed list of quotes as JSON, all of them or one by ID.
How to think about it. The tags come first, since
they decide what the client sees. Then the two helpers, copied from the
chapter, together with an errorReply struct for
writeError. The list handler is one line: the slice is
already the reply. The single-quote handler has the same three outcomes
as handleGetItem: a bad ID, no such quote, or the quote.
With no store, finding the quote is the search loop from Chapter 20. The
quotes never change, so the handlers can read them with no mutex, as in
Chapter 44.
Worked solution.
type quote struct {
ID int `json:"id"`
Text string `json:"text"`
Author string `json:"author"`
}
type errorReply struct {
Error string `json:"error"`
}
func handleListQuotes(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, quotes)
}
func handleGetQuote(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
writeError(w, http.StatusBadRequest, "the id must be a whole number")
return
}
for _, q := range quotes {
if q.ID == id {
writeJSON(w, http.StatusOK, q)
return
}
}
writeError(w, http.StatusNotFound, fmt.Sprintf("no quote has the id %d", id))
}writeJSON and writeError are the ones from
the chapter, unchanged. The results:
curl.exe -i http://localhost:8080/api/quotes/2
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 2,
"text": "Errors are values.",
"author": "Rob Pike"
}
curl.exe -i http://localhost:8080/api/quotes/9
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": "no quote has the id 9"
}
curl.exe -i http://localhost:8080/api/quotes/abc
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": "the id must be a whole number"
}
The return inside the loop matters. Without it, the
handler goes on after the loop and writes a 404 after the quote. Go then
prints superfluous response.WriteHeader call in the
terminal, as in Chapter 41.
Common mistakes.
- A tag with a space, such as
json: "text". Go does not complain, the tag is ignored, and the JSON says"Text". - Writing the not-found reply inside the loop, in an
else. Then the first quote that does not match sends a 404, and the loop never reaches the right one. - Sending errors with
http.Error. It works, but the body is plain text, and a client that expects JSON cannot read it. In an API, every reply should be JSON.
Problem 2 — A temperature API
Problem. Convert a temperature sent as JSON, and refuse bad input with a clear message.
How to think about it. Two structs: one for the
request and one for the reply. The tricky part is a missing
celsius. With a plain float64 field,
{} decodes to 0, and the server would happily
answer 32 °F. A pointer field starts as nil, and the
decoder only fills it when the field is there. So nil means
missing, and 0 means a real zero. After that, the handler
has the same steps as handleCreateItem: decode, check,
reply. Rounding to one decimal place is
math.Round(x*10) / 10 from Chapter 13.
Worked solution.
const maxBodyBytes = 1024
const absoluteZero = -273.15
// convertRequest uses a pointer, so that a missing celsius is nil and not 0.
type convertRequest struct {
Celsius *float64 `json:"celsius"`
}
type convertReply struct {
Celsius float64 `json:"celsius"`
Fahrenheit float64 `json:"fahrenheit"`
}
func handleConvert(w http.ResponseWriter, r *http.Request) {
var input convertRequest
err := readJSON(w, r, &input)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON: "+err.Error())
return
}
if input.Celsius == nil {
writeError(w, http.StatusBadRequest, "celsius is missing")
return
}
celsius := *input.Celsius
if celsius < absoluteZero {
writeError(w, http.StatusBadRequest, "celsius cannot be below -273.15")
return
}
fahrenheit := celsius*9/5 + 32
fahrenheit = math.Round(fahrenheit*10) / 10
writeJSON(w, http.StatusOK, convertReply{Celsius: celsius, Fahrenheit: fahrenheit})
}readJSON, writeJSON and
writeError are the chapter's, with the smaller limit. To
try it with curl.exe, put each body in a file, as the
chapter did, and send it with -d "@file". The replies:
| Body | Status | Reply |
|---|---|---|
{"celsius": 21.5} |
200 | {"celsius": 21.5, "fahrenheit": 70.7} |
{"celsius": 0} |
200 | {"celsius": 0, "fahrenheit": 32} |
{"celsius": -40} |
200 | {"celsius": -40, "fahrenheit": -40} |
{} |
400 | celsius is missing |
{"celsius": -300} |
400 | celsius cannot be below -273.15 |
{"celsius": 20, "kelvin": 293} |
400 | invalid JSON: json: unknown field "kelvin" |
The replies are indented in the real output. JSON writes
32.0 as 32: in JSON, a number is just a
number. The next chapter's homework writes a Go client for this
server.
Common mistakes.
- A plain
float64field.{}gives 32 °F, with status 200, and the client never learns that it forgot the temperature. - Reading
*input.Celsiusbefore checking fornil. A body of{}then crashes the handler withinvalid memory address or nil pointer dereference. Thenet/httppackage catches the crash and closes the connection, so the client gets no reply at all. - Rounding with
float64(int(x*10)) / 10. That cuts off instead of rounding, and goes the wrong way for negative numbers.
Problem 3 — Test a counter API
Problem. Write tests for a finished server with
httptest.
How to think about it. The send helper
is given, so each test is: reset the counter, send requests, check what
came back. Every reply is {"value": N}, so a second helper
that decodes it saves repeating the same five lines in every test.
Compare the decoded number, not the text: the server indents its JSON,
and a test that compares strings breaks when the spacing changes. For
bad input, a table with one row per body, as in the chapter. Each
subtest resets the counter, so that one row cannot affect the next.
Worked solution.
// readValue decodes a {"value": N} body, and stops the test if it cannot.
func readValue(t *testing.T, response *httptest.ResponseRecorder) int {
t.Helper()
var reply valueReply
err := json.Unmarshal(response.Body.Bytes(), &reply)
if err != nil {
t.Fatalf("the body %q is not a value: %v", response.Body, err)
}
return reply.Value
}
func TestGetStartsAtZero(t *testing.T) {
count = &counter{}
response := send("GET", "/api/counter", "")
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", response.Code, http.StatusOK)
}
if got := response.Header().Get("Content-Type"); got != "application/json" {
t.Errorf("Content-Type = %q, want application/json", got)
}
if got := readValue(t, response); got != 0 {
t.Errorf("value = %d, want 0", got)
}
}
func TestAddThenGet(t *testing.T) {
count = &counter{}
response := send("POST", "/api/counter/add", `{"by": 5}`)
if response.Code != http.StatusOK {
t.Fatalf("first add: status = %d, want %d", response.Code, http.StatusOK)
}
if got := readValue(t, response); got != 5 {
t.Errorf("first add: value = %d, want 5", got)
}
send("POST", "/api/counter/add", `{"by": 3}`)
response = send("GET", "/api/counter", "")
if got := readValue(t, response); got != 8 {
t.Errorf("value = %d, want 8", got)
}
}
func TestAddRejectsBadInput(t *testing.T) {
tests := []struct {
name string
body string
}{
{"not JSON", `hello`},
{"unknown field", `{"by": 5, "times": 2}`},
{"zero", `{"by": 0}`},
{"too big", `{"by": 101}`},
{"text", `{"by": "five"}`},
{"empty body", ``},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
count = &counter{}
response := send("POST", "/api/counter/add", test.body)
if response.Code != http.StatusBadRequest {
t.Errorf("status = %d, want %d", response.Code, http.StatusBadRequest)
}
if count.Value() != 0 {
t.Errorf("the counter changed to %d", count.Value())
}
})
}
}go test -v ends with:
PASS
ok countertest 0.180s
t.Helper() marks readValue
as a helper. When its t.Fatalf fails, Go reports the line
in the test that called readValue, not the line
inside the helper, which is the line you want to see.
To check that the tests really test something, break the server:
change by < 1 to by < 0 in
handleAdd. The zero subtest must now fail.
Common mistakes.
- Not resetting
countat the start of each test.TestAddThenGetthen depends on what earlier tests added, and the result changes if you run it alone withgo test -run TestAddThenGet. - Comparing the body with
{"value":8}. The server indents its JSON, so the text is different and the test fails, although the server is right. - Checking only the status for bad input. The counter could still have changed, and that is the bug that matters most.
Challenge — Update an item
Problem. Add PUT /api/items/{id} to the
items API, with a store method, a handler and tests.
How to think about it. Start at the bottom, in the
store, as the starter suggests. Update is
Delete with a different change: find the index, make a
copy, change the copy, save it, and only then replace the list in
memory. Changing s.items before saving would leave memory
and file out of step if the save failed. The handler joins two handlers
you already have: it reads the ID like handleGetItem, and
reads and checks the body like handleCreateItem. Read the
ID first, so that a bad ID is refused before the body is read. The reply
is 200, not 201, because nothing new was created.
Worked solution. In store.go:
func (s *itemStore) Update(id int, name string, quantity int) (item, error) {
s.mu.Lock()
defer s.mu.Unlock()
index := -1
for i, it := range s.items {
if it.ID == id {
index = i
}
}
if index == -1 {
return item{}, errNotFound
}
updated := slices.Clone(s.items)
updated[index].Name = name
updated[index].Quantity = quantity
err := s.save(updated, s.nextID)
if err != nil {
return item{}, err
}
s.items = updated
return updated[index], nil
}In main.go:
func handleUpdateItem(w http.ResponseWriter, r *http.Request) {
id, ok := readID(w, r)
if !ok {
return
}
var input itemInput
err := readJSON(w, r, &input)
var tooBig *http.MaxBytesError
if errors.As(err, &tooBig) {
writeError(w, http.StatusRequestEntityTooLarge,
fmt.Sprintf("the body can be at most %d bytes", tooBig.Limit))
return
}
if err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON: "+err.Error())
return
}
input.Name = strings.TrimSpace(input.Name)
err = checkInput(input)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
updated, err := store.Update(id, input.Name, input.Quantity)
if errors.Is(err, errNotFound) {
writeError(w, http.StatusNotFound, fmt.Sprintf("no item has the id %d", id))
return
}
if err != nil {
fmt.Println("Save error:", err)
writeError(w, http.StatusInternalServerError, "the item could not be saved")
return
}
writeJSON(w, http.StatusOK, updated)
}In main_test.go, one test for success, and a table for
the ways it can fail. Each row starts with one item, sends a bad
PUT, and checks that the item did not change:
func TestUpdate(t *testing.T) {
useTempStore(t)
send("POST", "/api/items", `{"name": "Rice", "quantity": 2}`)
response := send("PUT", "/api/items/1", `{"name": "Brown rice", "quantity": 5}`)
if response.Code != http.StatusOK {
t.Fatalf("PUT status = %d, want %d; body %s", response.Code, http.StatusOK, response.Body)
}
got, err := store.Get(1)
if err != nil {
t.Fatalf("Get: %v", err)
}
want := item{ID: 1, Name: "Brown rice", Quantity: 5}
if got != want {
t.Errorf("after PUT, item = %+v, want %+v", got, want)
}
}
func TestUpdateRejects(t *testing.T) {
tests := []struct {
name string
target string
body string
want int
}{
{"no such item", "/api/items/9", `{"name": "Tea", "quantity": 1}`, http.StatusNotFound},
{"bad id", "/api/items/abc", `{"name": "Tea", "quantity": 1}`, http.StatusBadRequest},
{"empty name", "/api/items/1", `{"name": "", "quantity": 1}`, http.StatusBadRequest},
{"unknown field", "/api/items/1", `{"name": "Tea", "quantity": 1, "id": 5}`, http.StatusBadRequest},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
useTempStore(t)
send("POST", "/api/items", `{"name": "Rice", "quantity": 2}`)
response := send("PUT", test.target, test.body)
if response.Code != test.want {
t.Errorf("status = %d, want %d; body %s", response.Code, test.want, response.Body)
}
got, err := store.Get(1)
if err != nil || got.Name != "Rice" {
t.Errorf("the item changed to %+v", got)
}
})
}
}TestUpdate checks the store, not only the reply: a
handler could send back the right JSON without saving anything. The
unknown field row shows that a client cannot change an ID
by sending one, because itemInput has no ID
field.
Common mistakes.
- Changing the item in a
for _, it := range s.itemsloop withit.Name = name.itis a copy, as in Chapter 22, so the list does not change, and the reply still shows the old name. - Changing
s.itemsdirectly and saving afterwards. If the save fails, the client gets 500, but the change is still in memory, and the nextGETshows it. - Forgetting the route. The handler compiles, but every
PUTgets 405 from the router. - Replying 201 Created. Nothing was created, so the right code is 200.
Done?
You can now build a JSON API: tagged structs, strict decoding, routes by method and path, the right status codes, and tests that need no running server. The next chapter, Chapter 46 — Calling an API, writes Go programs that talk to it.