46. Calling an API
The last chapter built a server that speaks JSON, and you talked to
it with curl.exe. This chapter writes the other side in Go:
programs that send requests, read the replies, and cope when things go
wrong. The server is slow, the server is down, the server says no. A
good client handles all three.
Every example talks to the items API from Chapter 45, so start it first, in its own terminal, and leave it running:
cd exercises/45/03-items-api
go run .
Then open a second terminal, which starts in go-work,
and run the examples there. The outputs below assume the two items left
at the end of Chapter 45: Rice, with ID 1, and Green tea, with ID 2. If
you added more, you will see more.
A client with a time limit
The net/http package has a client as well as a server.
http.Client is a struct, and one setting
matters more than the others:
client := &http.Client{Timeout: 10 * time.Second}Timeout is the most time one request may take, from
sending it to reading the end of the reply. If the server takes longer,
the request fails with an error.
There is also a ready-made client, http.DefaultClient,
and shortcuts such as http.Get(url) that use it. Its
Timeout is 0, which means no limit at all.
A server that accepts the connection and then never answers would keep
your program waiting forever. So make your own client with a timeout,
once, and use it for every request. One client can be used by many
goroutines at the same time.
Asking for a list
This is exercises/46/01-list-items.go:
// item has only the fields this program uses. The server also sends "id",
// and the decoder skips it.
type item struct {
Name string `json:"name"`
Quantity int `json:"quantity"`
}
func listItems(ctx context.Context, client *http.Client, server string) ([]item, error) {
request, err := http.NewRequestWithContext(ctx, "GET", server+"/api/items", nil)
if err != nil {
return nil, fmt.Errorf("list items: %w", err)
}
response, err := client.Do(request)
if err != nil {
return nil, fmt.Errorf("list items: %w", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("list items: the server replied %s", response.Status)
}
var items []item
err = json.NewDecoder(response.Body).Decode(&items)
if err != nil {
return nil, fmt.Errorf("list items: %w", err)
}
return items, nil
}main reads a -server flag, as in Chapter
32, makes the client, and prints the items:
client := &http.Client{Timeout: 10 * time.Second}
items, err := listItems(context.Background(), client, *server)
if err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
fmt.Println("Items:", len(items))
for _, it := range items {
fmt.Printf(" %-12s %3d\n", it.Name, it.Quantity)
}Output:
Items: 2
Rice 2
Green tea 1
listItems has five steps, and every client function in
this chapter follows them:
- Make the request.
http.NewRequestWithContexttakes a context, the method, the URL, and a body. AGEThas no body, so the body isnil. The context is the one from Chapter 39: cancel it, and the request stops.context.Background()is a context that is never cancelled, so only the client's timeout applies here. - Send it.
client.Do(request)sends the request and waits for the reply. It returns an error only when there is no reply at all: the server is down, the address is wrong, or the time ran out. - Close the body.
response.Bodyis a reader, liker.Bodyon the server. It holds a network connection open until it is closed.defer response.Body.Close()comes right after the error check, likedefer f.Close()in Chapter 31. - Check the status. A 404 or a 500 is not an
error for
client.Do: the server did reply. Only you know which status you expect.response.Statusis the whole status line, such as404 Not Found, andresponse.StatusCodeis the number. - Decode.
json.NewDecoder(response.Body).Decode(&items)reads the JSON straight from the body.
The item here has no ID field, and the
server sends "id" anyway. The decoder skips fields it has
no place for, which is what a client should do: the server may add
fields later, and an old client should keep working. The server in
Chapter 45 was strict with DisallowUnknownFields, because a
stranger's mistake there would end up in its data. Be strict in what you
accept as a server, and relaxed in what you read as a client.
Stop the server with Ctrl+C, and run the program again. On Windows you get something like:
Error: list items: Get "http://localhost:8080/api/items": dial tcp [::1]:8080: connectex: No connection could be made because the target machine actively refused it.
The error names the step (list items), the method and
URL, and what went wrong: nothing was listening on that port. The exact
address in the middle can differ. Start the server again before you go
on.
Leaving out defer response.Body.Close() gives no error,
and a short program like this one still works. A program that makes many
requests slowly runs out of connections and memory, and then fails in
strange ways. Close every body, even when you do not read it.
Building a URL safely
The server can search: /api/items?q=tea. Gluing the
search onto the URL with + breaks as soon as the words
contain a space, a & or a #, since those
mean something in a URL. The package
net/url builds the URL properly. This is
exercises/46/02-search.go:
// searchURL returns server + /api/items?q=search, with the search encoded.
func searchURL(server string, search 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", search)
u.RawQuery = query.Encode()
return u.String(), nil
}url.Parsesplits an address into its parts, such as the host, the path and the query, and gives a*url.URL.u.JoinPath("api", "items")adds parts to the path, with exactly one/between them, whether or not the server address ends in/.url.Valuesis a map from names to values, the same type asr.URL.Query()on the server in Chapter 42.Setputs in one value.query.Encode()turns it into query text, and escapes anything that needs it.u.String()puts the parts back together into one address.
main joins the words on the command line with spaces and
searches for them:
go run exercises/46/02-search.go green tea
Asking for http://localhost:8080/api/items?q=green+tea
2: Green tea
In a query, a space is written as +. The server turns it
back into a space, finds the item, and the program prints its ID and
name. A search with no match prints Nothing found., because
the server sent [].
Run exercises/46/02-search.go with the words
salt & pepper, in double quotes so that PowerShell
passes them as they are. Look at the address it prints: what did
& become? Then change searchURL to build
the address with + only, and run it again.
Sending JSON
Creating an item takes a POST with a JSON body. This is
the function that does the work in
exercises/46/03-add-item.go:
func addItem(ctx context.Context, client *http.Client, server string, input itemInput) (item, error) {
body, err := json.Marshal(input)
if err != nil {
return item{}, fmt.Errorf("add item: %w", err)
}
request, err := http.NewRequestWithContext(ctx, "POST", server+"/api/items", bytes.NewReader(body))
if err != nil {
return item{}, fmt.Errorf("add item: %w", err)
}
request.Header.Set("Content-Type", "application/json")
response, err := client.Do(request)
if err != nil {
return item{}, fmt.Errorf("add item: %w", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusCreated {
return item{}, fmt.Errorf("add item: %w", readAPIError(response))
}
var created item
err = json.NewDecoder(response.Body).Decode(&created)
if err != nil {
return item{}, fmt.Errorf("add item: %w", err)
}
return created, nil
}The five steps are the same, with three changes:
- The body.
json.Marshalturns the input into bytes. A request body must be a reader, andbytes.NewReadermakes one from a[]byte, asstrings.NewReaderdoes from a string. - The header.
request.Header.Setsays that the body is JSON. It is the sameContent-Typethatcurl.exe -Hsent in Chapter 45. - The status. Success is 201 Created, not 200.
When the server says no, it sends {"error": "..."}. That
message is far more useful than 400 Bad Request alone, so
the program reads it into an error of its own type:
// apiError is a reply from the server that was not a success.
type apiError struct {
Status int
Message string
}
func (e *apiError) Error() string {
return fmt.Sprintf("the server replied %d: %s", e.Status, e.Message)
}
// readAPIError turns an error response into an *apiError. If the body is not
// the JSON the server usually sends, the status text is used instead.
func readAPIError(response *http.Response) error {
var reply errorReply
err := json.NewDecoder(response.Body).Decode(&reply)
if err != nil || reply.Error == "" {
return &apiError{Status: response.StatusCode, Message: http.StatusText(response.StatusCode)}
}
return &apiError{Status: response.StatusCode, Message: reply.Error}
}error is an interface with one method,
Error() string. Like any interface from Chapter 29, it is
satisfied by any type with that method, so *apiError is an
error, and it carries the status as a number. Not every error reply is
JSON: the 405 from the router in Chapter 45 was plain text. Then
Decode fails, and readAPIError falls back on
http.StatusText, which gives the standard
text for a status, such as Method Not Allowed.
addItem wraps the *apiError with
%w, so main can find it again with
errors.As, from Chapter 45, and treat a refusal differently
from a network failure:
created, err := addItem(context.Background(), client, *server, input)
var refused *apiError
if errors.As(err, &refused) && refused.Status == http.StatusBadRequest {
fmt.Fprintln(os.Stderr, "The server did not accept the item:", refused.Message)
os.Exit(1)
}
if err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
fmt.Printf("Added %s (quantity %d) with id %d.\n", created.Name, created.Quantity, created.ID)Three runs, the last two with bad input. With no -name,
the name is empty:
go run exercises/46/03-add-item.go -name Soap -quantity 3
Added Soap (quantity 3) with id 4.
go run exercises/46/03-add-item.go -quantity 3
The server did not accept the item: the name is empty
exit status 1
go run exercises/46/03-add-item.go -name Salt -quantity 5000
The server did not accept the item: the quantity must be from 1 to 1000
exit status 1
Soap gets the ID 4, because 3 was used in Chapter 45 and is never given out again. The client does not check the name or the quantity itself. The server checks them anyway, and the client passes the message on. Checking in both places would mean keeping two copies of the rules in step.
Many requests at once
A request spends almost all its time waiting for the network. Waiting
is something goroutines are good at, as Part 8 showed. This is
exercises/46/04-check-urls.go, which asks for several URLs
at the same time and reports how each went:
func check(client *http.Client, url string) result {
start := time.Now()
response, err := client.Get(url)
if err != nil {
return result{url: url, err: err, elapsed: time.Since(start)}
}
defer response.Body.Close()
return result{url: url, status: response.Status, elapsed: time.Since(start)}
}client.Get(url) is a shortcut for a GET
with no context, using your client and its timeout.
main starts one goroutine per URL with wg.Go,
from Chapter 36. Each one writes only its own place in the
results slice, so no mutex is needed, and the results come
out in the order of the URLs, whichever finished first:
client := &http.Client{Timeout: 5 * time.Second}
results := make([]result, len(urls))
start := time.Now()
var wg sync.WaitGroup
for i, url := range urls {
wg.Go(func() {
// Each goroutine writes only its own place in the slice.
results[i] = check(client, url)
})
}
wg.Wait()With no arguments, it checks five URLs on your own computer. The output looks like this, with times that differ on every run:
200 OK http://localhost:8080/api/items (2ms)
200 OK http://localhost:8080/api/items/1 (2ms)
404 Not Found http://localhost:8080/api/items/999 (2ms)
404 Not Found http://localhost:8080/nothing (2ms)
FAILED http://localhost:9999/
Get "http://localhost:9999/": dial tcp [::1]:9999: connectex: No connection could be made because the target machine actively refused it.
All done in 2.03s
Nothing listens on port 9999, so that request fails. On Windows, a refused connection can take about two seconds to be reported, and the whole run takes about as long as that one slow request, not the sum of all five. One after another, slow URLs would add up.
You can also pass your own URLs, such as https://go.dev,
if you are online. A program that checks hundreds of URLs should not
start hundreds of requests at once: use the worker pool from Chapter 38
to limit how many run at the same time.
A client type
The functions so far repeat the same steps, with the server address
and the client passed in every time.
exercises/46/05-items-client/ is a folder with its own
go.mod, and gathers all of it into one type, in
client.go:
// apiClient talks to the items server at baseURL.
type apiClient struct {
baseURL string
httpClient *http.Client
}
func newAPIClient(baseURL string) *apiClient {
return &apiClient{
baseURL: strings.TrimSuffix(baseURL, "/"),
httpClient: &http.Client{Timeout: 10 * time.Second},
}
}One method, do, holds the five steps once. It takes the
method and path, an input to send as JSON (or nil for
none), the status it expects, and a pointer to decode the reply into (or
nil):
func (c *apiClient) do(ctx context.Context, method string, path string, input any, want int, output any) error {
var body io.Reader
if input != nil {
data, err := json.Marshal(input)
if err != nil {
return err
}
body = bytes.NewReader(data)
}
request, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, body)
if err != nil {
return err
}
if input != nil {
request.Header.Set("Content-Type", "application/json")
}
response, err := c.httpClient.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode != want {
var reply errorReply
err := json.NewDecoder(response.Body).Decode(&reply)
if err != nil || reply.Error == "" {
return &apiError{Status: response.StatusCode, Message: http.StatusText(response.StatusCode)}
}
return &apiError{Status: response.StatusCode, Message: reply.Error}
}
if output != nil {
err = json.NewDecoder(response.Body).Decode(output)
if err != nil {
return fmt.Errorf("the reply is not valid JSON: %w", err)
}
}
return nil
}body is declared as an io.Reader and left
nil when there is no input, so that a GET
sends no body. Each public method is now a few lines, and says only what
is special about it:
// List returns every item.
func (c *apiClient) List(ctx context.Context) ([]item, error) {
var items []item
err := c.do(ctx, "GET", "/api/items", nil, http.StatusOK, &items)
if err != nil {
return nil, fmt.Errorf("list items: %w", err)
}
return items, nil
}
// Delete removes the item with this ID.
func (c *apiClient) Delete(ctx context.Context, id int) error {
path := fmt.Sprintf("/api/items/%d", id)
err := c.do(ctx, "DELETE", path, nil, http.StatusNoContent, nil)
if err != nil {
return fmt.Errorf("delete item %d: %w", id, err)
}
return nil
}Add is the same, with "POST", an
itemInput, and http.StatusCreated.
main.go turns the client into a command-line tool with
three commands, list, add and
delete, in the style of Chapter 32. Its context comes from
signal.NotifyContext, as in Chapter 39, so Ctrl+C cancels a
request that is still waiting. Run it from its folder:
cd exercises/46/05-items-client
go run . list
1 Rice 2
2 Green tea 1
4 Soap 3
go run . delete 9
Error: delete item 9: the server replied 404: no item has the id 9
exit status 1
go run . add Milk
Usage:
go run . [-server URL] list
go run . [-server URL] add NAME QUANTITY
go run . [-server URL] delete ID
-server string
address of the items server (default "http://localhost:8080")
exit status 2
The server's own message reaches the user, wrapped with what the client was doing.
Testing a client with httptest.NewServer
To test a client, you need a server, and the real one is not a good
choice: its data changes, and it might not be running. Chapter 45 used
httptest.NewRecorder to test handlers without a network.
For a client, httptest.NewServer does the
opposite: it starts a real server, on a free port of your own computer,
with a handler you write in the test. This is part of
exercises/46/05-items-client/client_test.go:
func TestList(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" || r.URL.Path != "/api/items" {
t.Errorf("got %s %s, want GET /api/items", r.Method, r.URL.Path)
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintln(w, `[{"id": 1, "name": "Rice", "quantity": 2}, {"id": 4, "name": "Tea", "quantity": 1}]`)
}))
defer server.Close()
items, err := newAPIClient(server.URL).List(context.Background())
if err != nil {
t.Fatalf("List: %v", err)
}
want := []item{{ID: 1, Name: "Rice", Quantity: 2}, {ID: 4, Name: "Tea", Quantity: 1}}
if len(items) != len(want) {
t.Fatalf("got %d items, want %d", len(items), len(want))
}
for i := range want {
if items[i] != want[i] {
t.Errorf("item %d = %+v, want %+v", i, items[i], want[i])
}
}
}http.HandlerFunc(...)turns a function literal into a handler. The fake server has one handler for every path, and that handler checks that the client asked for the right method and path.server.URLis the fake server's address, such ashttp://127.0.0.1:52817. The port is different each time, which is why the client takes its address as a parameter instead of havinglocalhost:8080written into it.defer server.Close()stops the server at the end of the test.
The fake server can also misbehave on purpose, which is hard to
arrange with a real one. TestErrorReplies is a table of
error replies: a JSON error with 400, one with 404, and plain text with
500. Each one must come back as an *apiError with the right
status and message. TestBadJSONReply sends HTML where JSON
was expected. And TestTimeout makes the server slower than
the client is willing to wait:
func TestTimeout(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(500 * time.Millisecond)
fmt.Fprintln(w, "[]")
}))
defer server.Close()
client := newAPIClient(server.URL)
client.httpClient.Timeout = 50 * time.Millisecond
_, err := client.List(context.Background())
if !errors.Is(err, context.DeadlineExceeded) {
t.Errorf("error = %v, want a timeout", err)
}
}The test is in the same package, so it can change the unexported
httpClient field and shorten the timeout to 50
milliseconds. A timeout error from http.Client matches
context.DeadlineExceeded, the same error a context from
Chapter 39 gives when its time is up, so errors.Is finds it
through all the wrapping.
Run the tests from the folder. The server from Chapter 45 does not need to be running:
go test -v
Every test passes. TestTimeout takes about half a
second, not 50 milliseconds: server.Close waits for the
sleeping handler to finish before it returns.
In exercises/46/05-items-client/client_test.go, make the
fake server in TestAddSendsJSON reply with
http.StatusOK instead of http.StatusCreated,
and run the tests. What does the failure say? Then, in
client.go, change the check in do from
response.StatusCode != want to
response.StatusCode < 200 || response.StatusCode > 299,
and run them again. Which is better: a strict client or a relaxed one?
Put both back.
Homework
Homework starters are in exercises/46/homework/. Each
one runs as it is, with a placeholder. Problems 1 and 2 talk to your
homework servers from Chapter 45: start the solution in
exercises/45/homework/solutions/ in another terminal first.
Problem 3 and the challenge use the items API from Chapter 45.
Problem 1 — A quote client
Open exercises/46/homework/01-quote-client.go. Write
getQuote, which asks the quotes server for
GET /api/quotes/{id} and decodes the quote. Any status
other than 200 is an error that names the status. main is
finished: it reads -id and prints the quote.
Problem 2 — A temperature client
Open exercises/46/homework/02-convert-client.go. Write
toFahrenheit, which sends {"celsius": C} to
POST /api/convert and returns the Fahrenheit value. When
the status is not 200, return an error with the status and the server's
message. main is finished: it converts five temperatures,
and the last one is refused.
Problem 3 — Many searches at once
Open exercises/46/homework/03-many-searches.go. Write
searchURL with url.Values, and
countMatches, which returns how many items a search found.
Then change the loop in main so that the five searches run
at the same time, one goroutine each.
Challenge — One item, tested
Open the folder exercises/46/homework/04-get-item, a
copy of the chapter's client. Add a Get method to the
client, a get ID command that prints
4: Soap, quantity 3, and two tests with
httptest.NewServer: one where the fake server sends an
item, and one where it replies 404 with an error message.
Stuck or done? Open the homework solutions page.