46. Calling an API — Homework solutions

The solutions are in exercises/46/homework/solutions/. Problems 1 to 3 are single files, run from go-work, and each needs a server running in another terminal, as the problem says. The challenge is a folder: cd into it, then use go run . (with the server running) or go test -v (no server needed).

Problem 1 — A quote client

Problem. Ask the quotes server for one quote, and decode it.

How to think about it. This is listItems from the chapter with a different path and a different type: make the request, send it, close the body, check the status, decode. The path holds the ID, so build it with fmt.Sprintf. An ID is a number, so it never needs escaping. Every error is wrapped with get quote N, so the user knows which request failed.

Start the server first, in another terminal:

go run exercises/45/homework/solutions/01-quotes-api.go

Worked solution.

func getQuote(ctx context.Context, client *http.Client, server string, id int) (quote, error) {
    address := fmt.Sprintf("%s/api/quotes/%d", server, id)
    request, err := http.NewRequestWithContext(ctx, "GET", address, nil)
    if err != nil {
        return quote{}, fmt.Errorf("get quote %d: %w", id, err)
    }

    response, err := client.Do(request)
    if err != nil {
        return quote{}, fmt.Errorf("get quote %d: %w", id, err)
    }
    defer response.Body.Close()

    if response.StatusCode != http.StatusOK {
        return quote{}, fmt.Errorf("get quote %d: the server replied %s", id, response.Status)
    }

    var q quote
    err = json.NewDecoder(response.Body).Decode(&q)
    if err != nil {
        return quote{}, fmt.Errorf("get quote %d: %w", id, err)
    }
    return q, nil
}

Two runs:

go run exercises/46/homework/solutions/01-quote-client.go -id 2
"Errors are values."
  - Rob Pike

go run exercises/46/homework/solutions/01-quote-client.go -id 9
Error: get quote 9: the server replied 404 Not Found
exit status 1

Common mistakes.

  • Leaving out the status check. For -id 9, the server sends {"error": "..."}, which decodes into a quote with no error, since a client ignores unknown fields. The program prints an empty quote, "", and claims success.
  • Putting defer response.Body.Close() before the error check. When client.Do fails, response is nil, and the program crashes when the deferred call runs.
  • Using http.Get, which has no timeout. It works here, but main made a client with a timeout for a reason.

Problem 2 — A temperature client

Problem. Send a temperature as JSON with POST, and read either the answer or the server's error message.

How to think about it. This is addItem from the chapter: marshal the request, wrap the bytes in bytes.NewReader, set the Content-Type, send. The status to expect is 200, since nothing is created. On any other status, decode errorReply from the body, and fall back on the status line when the body is not the expected JSON, as readAPIError does. The client's convertRequest has a plain float64. The pointer was the server's problem, because the server must tell "missing" from 0. The client always sends a value.

Start the server first, in another terminal:

go run exercises/45/homework/solutions/02-convert-api.go

Worked solution.

func toFahrenheit(ctx context.Context, client *http.Client, server string, celsius float64) (float64, error) {
    body, err := json.Marshal(convertRequest{Celsius: celsius})
    if err != nil {
        return 0, fmt.Errorf("convert: %w", err)
    }

    request, err := http.NewRequestWithContext(ctx, "POST", server+"/api/convert", bytes.NewReader(body))
    if err != nil {
        return 0, fmt.Errorf("convert: %w", err)
    }
    request.Header.Set("Content-Type", "application/json")

    response, err := client.Do(request)
    if err != nil {
        return 0, fmt.Errorf("convert: %w", err)
    }
    defer response.Body.Close()

    if response.StatusCode != http.StatusOK {
        var reply errorReply
        err := json.NewDecoder(response.Body).Decode(&reply)
        if err != nil || reply.Error == "" {
            return 0, fmt.Errorf("convert: the server replied %s", response.Status)
        }
        return 0, fmt.Errorf("convert: the server replied %d: %s", response.StatusCode, reply.Error)
    }

    var reply convertReply
    err = json.NewDecoder(response.Body).Decode(&reply)
    if err != nil {
        return 0, fmt.Errorf("convert: %w", err)
    }
    return reply.Fahrenheit, nil
}

Output:

 -40.0 C =  -40.0 F
   0.0 C =   32.0 F
  21.5 C =   70.7 F
 100.0 C =  212.0 F
-300.0 C: convert: the server replied 400: celsius cannot be below -273.15

The rounding to one decimal place is done by the server. The client only prints.

Common mistakes.

  • Passing body itself to http.NewRequestWithContext. A []byte is not a reader, and Go stops with cannot use body (variable of type []byte) as io.Reader value.
  • Forgetting the Content-Type header. This server does not check it, so the program still works, but other servers refuse a JSON body without it.
  • Expecting 201, as in the chapter. Every conversion then looks like an error, with the message the server replied 200 OK.

Problem 3 — Many searches at once

Problem. Build search URLs safely, count the results, and run the searches at the same time.

How to think about it. Three separate jobs. searchURL is the chapter's function, unchanged. countMatches is a GET that decodes a list and returns its length. For the goroutines, follow 04-check-urls.go: give each search its own place in counts and in errs, so that no two goroutines write the same variable, and no mutex is needed. Since Go 1.22, each round of the loop has its own i and word, so each goroutine sees the right ones.

Start the Chapter 45 items server first, in another terminal.

Worked solution.

func searchURL(server string, words string) (string, error) {
    u, err := url.Parse(server)
    if err != nil {
        return "", fmt.Errorf("the server address %q is not valid: %w", server, err)
    }
    u = u.JoinPath("api", "items")

    query := url.Values{}
    query.Set("q", words)
    u.RawQuery = query.Encode()

    return u.String(), nil
}

func countMatches(ctx context.Context, client *http.Client, address string) (int, error) {
    request, err := http.NewRequestWithContext(ctx, "GET", address, nil)
    if err != nil {
        return 0, err
    }

    response, err := client.Do(request)
    if err != nil {
        return 0, err
    }
    defer response.Body.Close()

    if response.StatusCode != http.StatusOK {
        return 0, fmt.Errorf("the server replied %s", response.Status)
    }

    var items []item
    err = json.NewDecoder(response.Body).Decode(&items)
    if err != nil {
        return 0, err
    }
    return len(items), nil
}

And in main, in place of the loop that ran the searches one after another:

var wg sync.WaitGroup
for i, word := range words {
    wg.Go(func() {
        // Each goroutine writes only its own place in the slices.
        counts[i], errs[i] = searchOne(ctx, client, *server, word)
    })
}
wg.Wait()

With the items from the chapter, Rice, Green tea and Soap, the output is:

"rice"          1 found
"tea"           1 found
"green tea"     1 found
"salt & pepper" 0 found
"SOAP"          1 found

SOAP finds Soap because the server lowercases both sides. The results come out in the order of the words, whichever search finished first.

Common mistakes.

  • Building the address with server + "/api/items?q=" + words. In salt & pepper, the & starts a new query parameter, so the server searches for salt only, and the spaces are not allowed in a URL at all.
  • Using append from the goroutines to collect results. That is the shared-slice race from Chapter 38, and go run -race reports it.
  • Forgetting wg.Wait(). main prints before the searches finish, so most counts show 0, and the race detector reports a data race.

Challenge — One item, tested

Problem. Add Get to the client, a get command, and tests against a fake server.

How to think about it. With do in place, Get is List with a path that holds the ID, like Delete, and an item to decode into. The get command copies delete: check that there is exactly one argument, turn it into a number, call the client. For the tests, copy TestList and TestErrorReplies. The fake server in TestGet checks the method and path it was sent, so that a wrong path in Get fails the test. TestGetNotFound checks that the server's message survives the trip into an *apiError.

Worked solution. In client.go:

// Get returns the item with this ID.
func (c *apiClient) Get(ctx context.Context, id int) (item, error) {
    var it item
    path := fmt.Sprintf("/api/items/%d", id)
    err := c.do(ctx, "GET", path, nil, http.StatusOK, &it)
    if err != nil {
        return item{}, fmt.Errorf("get item %d: %w", id, err)
    }
    return it, nil
}

In run, in main.go:

case "get":
    if len(args) != 2 {
        return errUsage
    }
    id, err := strconv.Atoi(args[1])
    if err != nil {
        return fmt.Errorf("the id %q is not a whole number", args[1])
    }
    it, err := client.Get(ctx, id)
    if err != nil {
        return err
    }
    fmt.Printf("%d: %s, quantity %d\n", it.ID, it.Name, it.Quantity)
    return nil

In client_test.go:

func TestGet(t *testing.T) {
    server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if r.Method != "GET" || r.URL.Path != "/api/items/4" {
            t.Errorf("got %s %s, want GET /api/items/4", r.Method, r.URL.Path)
        }
        w.Header().Set("Content-Type", "application/json")
        fmt.Fprintln(w, `{"id": 4, "name": "Soap", "quantity": 3}`)
    }))
    defer server.Close()

    got, err := newAPIClient(server.URL).Get(context.Background(), 4)
    if err != nil {
        t.Fatalf("Get: %v", err)
    }
    want := item{ID: 4, Name: "Soap", Quantity: 3}
    if got != want {
        t.Errorf("got %+v, want %+v", got, want)
    }
}

func TestGetNotFound(t *testing.T) {
    server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        w.WriteHeader(http.StatusNotFound)
        fmt.Fprintln(w, `{"error": "no item has the id 9"}`)
    }))
    defer server.Close()

    _, err := newAPIClient(server.URL).Get(context.Background(), 9)

    var replyErr *apiError
    if !errors.As(err, &replyErr) {
        t.Fatalf("error = %v, want an *apiError", err)
    }
    if replyErr.Status != http.StatusNotFound {
        t.Errorf("Status = %d, want %d", replyErr.Status, http.StatusNotFound)
    }
    want := "no item has the id 9"
    if replyErr.Message != want {
        t.Errorf("Message = %q, want %q", replyErr.Message, want)
    }
}

With the Chapter 45 server running:

go run . get 4
4: Soap, quantity 3

go run . get 9
Error: get item 9: the server replied 404: no item has the id 9
exit status 1

go test -v passes all the tests, with or without the server running.

Common mistakes.

  • In the fake server, calling w.WriteHeader after fmt.Fprintln. The status is then already 200, the client decodes the error JSON as an item, and TestGetNotFound fails with want an *apiError. Headers, then status, then body, as in Chapter 41.
  • Writing t.Fatalf inside the fake server's handler. The handler runs in another goroutine, and t.Fatalf may only be called from the test's own goroutine. Use t.Errorf there.

Done?

Your programs can now call an API: with a timeout, a safe URL, JSON in both directions, the status checked, the server's message passed on, several requests at once, and tests that need no real server. The next chapter, Chapter 47 — Logging, configuration and shipping, gets a program ready to run for real: log lines instead of fmt.Println, settings from outside the code, and a .exe to hand to someone else.