45. Building a JSON API

Part 9 built pages for people: a browser asks, and the server replies with HTML. Part 10 is about the apps that people actually run, and many of those talk to programs, not people. A phone app, a script, or another server asks for data, gets it back as JSON, and decides for itself how to show it. A server that answers programs like this is called an API (application programming interface).

This chapter builds a JSON API for a shopping list, and tests it without starting a server at all. The next chapter writes the other side: a Go program that calls it.

Pages for people, data for programs

The server in this chapter has no HTML and no forms. Each route takes JSON, gives JSON, or both:

Route What it does
GET /api/items Replies with every item, as a JSON array. ?q=tea keeps only the items whose name contains tea.
GET /api/items/{id} Replies with one item.
POST /api/items Creates an item from the JSON in the body, and replies with it.
DELETE /api/items/{id} Removes an item.

The method says what to do, and the path says which thing. GET and POST on the same path do different jobs, and DELETE is a method you have not used before: it asks the server to remove something. The paths start with /api/, a common habit that keeps the API apart from any pages the same server might have.

An item in JSON looks like this:

{
  "id": 1,
  "name": "Rice",
  "quantity": 2
}

The names are lowercase. In Chapter 44, the JSON used the Go field names, such as "Text", because the file was only read by your own program. An API is read by other people's programs, so you pick the names yourself, and keep them the same forever.

Struct tags

A field must be exported, with a capital letter, for encoding/json to see it. A struct tag gives it a different name in JSON. This is exercises/45/01-struct-tags.go, which has no server:

type item struct {
    ID       int    `json:"id"`
    Name     string `json:"name"`
    Quantity int    `json:"quantity"`
    Note     string `json:"note,omitempty"`
}

func show(value any) {
    data, err := json.Marshal(value)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println(string(data))
}

func main() {
    show(item{ID: 1, Name: "Rice", Quantity: 2})
    show(item{ID: 2, Name: "Tea", Quantity: 1, Note: "green"})

    var fromText item
    text := `{"name": "Soap", "colour": "white"}`
    err := json.Unmarshal([]byte(text), &fromText)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Printf("%+v\n", fromText)

    var none []item
    show(none)
    show([]item{})
}

Output:

{"id":1,"name":"Rice","quantity":2}
{"id":2,"name":"Tea","quantity":1,"note":"green"}
{ID:0 Name:Soap Quantity:0 Note:}
null
[]

A tag is the text in backquotes after the type. It is not code: it is a note that packages can read, and encoding/json reads the part that starts with json:. Write it exactly like this, with no spaces around the colon. A typo such as json: "id" gives no error, and the tag is simply ignored.

  • json:"id" gives the field the name id in JSON, both when writing and when reading.
  • ,omitempty leaves the field out when it holds the zero value, here an empty string. The first item has no note at all.
  • json.Marshal is json.MarshalIndent from Chapter 44 without the line breaks. Programs do not need them, but the server in this chapter still indents its replies, so that you can read them.
  • any is a short name for interface{}, the empty interface: a parameter of type any accepts a value of any type. json.Marshal itself takes an any.

The third line shows what json.Unmarshal does with JSON that does not fit the struct. "colour" has no field, so it is skipped with no error. id and quantity are missing, so they keep their zero values. For a file your own program wrote, that is convenient. For a request from a stranger, it hides mistakes, as the next section shows.

The last two lines are a trap. A slice that was declared and never filled is nil, and JSON shows nil as null. An empty slice made with []item{} is []. A program that asks for a list expects a list, even an empty one, and some will break on null. So an API should always send an empty slice, never a nil one.

In exercises/45/01-struct-tags.go, remove ,omitempty from the tag of Note and run the program again. Then change json:"name" to json:"Name". What changes in the output?

Reading JSON strictly

A client can send anything: the wrong type, a misspelled field, half an object, or nothing. A server should refuse all of those with a clear message, instead of saving an item with a quantity of 0. This is exercises/45/02-strict-decoding.go, again with no server:

type itemInput struct {
    Name     string `json:"name"`
    Quantity int    `json:"quantity"`
}

// decodeInput reads exactly one JSON object with only known fields.
func decodeInput(body io.Reader) (itemInput, error) {
    var input itemInput

    decoder := json.NewDecoder(body)
    decoder.DisallowUnknownFields()

    err := decoder.Decode(&input)
    if err != nil {
        return itemInput{}, err
    }

    // A second Decode must find nothing at all, or there was extra data.
    err = decoder.Decode(&struct{}{})
    if !errors.Is(err, io.EOF) {
        return itemInput{}, errors.New("the body must hold one JSON object only")
    }
    return input, nil
}

main tries six bodies, each one something a client might send:

bodies := []string{
    `{"name": "Rice", "quantity": 2}`,
    `{"name": "Rice", "quantity": "two"}`,
    `{"name": "Rice", "colour": "white"}`,
    `{"name": "Rice"`,
    ``,
    `{"name": "Rice"} {"name": "Tea"}`,
}

Output:

OK: {Name:Rice Quantity:2}
Error: json: cannot unmarshal string into Go struct field itemInput.quantity of type int
Error: json: unknown field "colour"
Error: unexpected EOF
Error: EOF
Error: the body must hold one JSON object only

Only the first body gets through. Here is what is new:

  • io.Reader is an interface from the io package for anything you can read bytes from, a little at a time: an open file, a string through strings.NewReader, or the body of a request. decodeInput does not care which.
  • json.NewDecoder(body) makes a decoder that reads JSON from a reader. json.Unmarshal needs all the bytes in a slice first. A request body arrives as a reader, so a decoder is the natural fit.
  • decoder.DisallowUnknownFields() turns a field with no match in the struct into an error. Without it, {"name": "Rice", "qty": 2} would be accepted with a quantity of 0, and the client would never learn about the typo.
  • decoder.Decode(&input) reads one JSON value and fills input, like json.Unmarshal.
  • The second Decode checks that nothing comes after the object. When the reader has nothing left, Decode returns io.EOF ("end of file"). Anything else, such as a second object, is refused. &struct{}{} is a pointer to an empty struct, a place to decode into that keeps nothing.

The two short errors deserve a word. unexpected EOF means the JSON stopped in the middle. A plain EOF from the first Decode means the body was empty.

The items API

Now the real server. It is a folder with its own go.mod, in exercises/45/03-items-api/, because it has two source files and a test file:

File What it holds
store.go The items, kept in memory and in items.json, safe for many requests.
main.go The handlers, the routes, and main.
main_test.go The tests, at the end of this chapter.

store.go puts together what Part 8 and Chapter 44 taught. The items live inside a struct with a mutex, as in Chapter 38, and every change is saved through a temporary file, as in Chapter 44:

type item struct {
    ID       int    `json:"id"`
    Name     string `json:"name"`
    Quantity int    `json:"quantity"`
}

// storeFile is what the JSON file holds.
type storeFile struct {
    NextID int    `json:"next_id"`
    Items  []item `json:"items"`
}

// itemStore keeps the items in memory and in a JSON file. Its methods are
// safe to call from many requests at the same time.
type itemStore struct {
    path string

    mu     sync.Mutex // protects the fields below
    items  []item
    nextID int
}

Each item gets an ID, a number the server chooses, which never changes and is never used again. nextID is the next one to hand out, and it is saved in the file too, so that a deleted item's ID is not reused after a restart. The methods are:

Method What it does
openItemStore(path) Loads the file. A missing file means an empty store.
All() Returns a copy of every item.
Get(id) Returns one item, or errNotFound.
Add(name, quantity) Gives the item the next ID, saves, and returns it.
Delete(id) Removes one item and saves, or returns errNotFound.

errNotFound is a sentinel error, made with errors.New, as in Chapter 33. The handlers check for it with errors.Is. Here is Add:

// Add gives the item the next ID, saves, and returns it with its ID.
func (s *itemStore) Add(name string, quantity int) (item, error) {
    s.mu.Lock()
    defer s.mu.Unlock()

    it := item{ID: s.nextID, Name: name, Quantity: quantity}
    updated := append(slices.Clone(s.items), it)

    err := s.save(updated, s.nextID+1)
    if err != nil {
        return item{}, err
    }
    s.items = updated
    s.nextID++
    return it, nil
}

The order matters. Add builds the new list in a copy, saves the copy, and only then replaces the list in memory. If the save fails, the memory still matches the file, and the client is told that nothing was added. All returns a copy for a similar reason: a handler can look through it after the lock is released, while another request changes the real list.

The variable is called it and not item, because item is the name of the type.

Routes with a method and an ID

At the bottom of main.go, one function connects every pattern to its handler:

// routes connects every pattern to its handler.
func routes() *http.ServeMux {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /api/items", handleListItems)
    mux.HandleFunc("GET /api/items/{id}", handleGetItem)
    mux.HandleFunc("POST /api/items", handleCreateItem)
    mux.HandleFunc("DELETE /api/items/{id}", handleDeleteItem)
    return mux
}

These are the patterns from Chapters 41 and 42: a method, a space, and a path with an optional wildcard. What is new is the http.ServeMux, the router. Until now you called http.HandleFunc, which adds a route to a router that the http package keeps for you, and passed nil to http.ListenAndServe to use it. http.NewServeMux() makes a router of your own, with the same HandleFunc method. main passes it to the server:

err = http.ListenAndServe("localhost:8080", routes())

Why bother? Because the tests can call routes() too, and get a fresh router with exactly the routes the real server has.

{id} is a string, like every wildcard. readID turns it into a number, and replies by itself when it cannot:

// readID reads the {id} part of the path. On failure it has already replied.
func readID(w http.ResponseWriter, r *http.Request) (int, bool) {
    id, err := strconv.Atoi(r.PathValue("id"))
    if err != nil {
        writeError(w, http.StatusBadRequest, "the id must be a whole number")
        return 0, false
    }
    return id, true
}

It returns a bool that says whether it worked, so the handler knows whether to stop.

Writing JSON replies

Every reply in this API is JSON, errors included. Two small functions take care of that:

// writeJSON sends value as JSON with the given status.
func writeJSON(w http.ResponseWriter, status int, value any) {
    data, err := json.MarshalIndent(value, "", "  ")
    if err != nil {
        fmt.Println("JSON error:", err)
        http.Error(w, "Internal Server Error", http.StatusInternalServerError)
        return
    }
    data = append(data, '\n')

    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(status)
    // An error here means the client has gone, so there is no one to tell.
    w.Write(data)
}

// writeError sends {"error": message} with the given status.
func writeError(w http.ResponseWriter, status int, message string) {
    writeJSON(w, status, errorReply{Error: message})
}

errorReply is a struct with one field, tagged json:"error". writeJSON follows the order from Chapter 41: headers, then status, then body. It turns the value into JSON before it writes anything. If that failed halfway through writing, the client would already have status 200 and half a reply. Marshaling first means it can still send a clean 500. The header Content-Type: application/json tells the client that the body is JSON. A newline at the end makes the reply look tidy in a terminal.

With these, the list handler is short:

func handleListItems(w http.ResponseWriter, r *http.Request) {
    items := store.All()

    search := strings.ToLower(r.URL.Query().Get("q"))
    if search != "" {
        found := []item{}
        for _, it := range items {
            if strings.Contains(strings.ToLower(it.Name), search) {
                found = append(found, it)
            }
        }
        items = found
    }

    writeJSON(w, http.StatusOK, items)
}

r.URL.Query().Get("q") is the query string from Chapter 42. found starts as []item{}, not nil, so a search with no matches gives [], never null. openItemStore starts with []item{} too, for the same reason.

Reading the request body

readJSON is decodeInput from the start of the chapter, made general and given a size limit:

// readJSON decodes the request body into dst. It allows one JSON value of
// at most maxBodyBytes, with no fields that dst does not have.
func readJSON(w http.ResponseWriter, r *http.Request, dst any) error {
    r.Body = http.MaxBytesReader(w, r.Body, maxBodyBytes)

    decoder := json.NewDecoder(r.Body)
    decoder.DisallowUnknownFields()

    err := decoder.Decode(dst)
    if err != nil {
        return err
    }
    err = decoder.Decode(&struct{}{})
    if !errors.Is(err, io.EOF) {
        return errors.New("the body must hold one JSON object only")
    }
    return nil
}

r.Body is the body of the request, an io.Reader. Nothing stops a client from sending a gigabyte. http.MaxBytesReader wraps the body so that reading more than maxBodyBytes (4096 here) fails with an error. An item is a few dozen bytes, so 4 KB is plenty. dst is an any, so that one function can fill any struct. The caller passes a pointer, as for json.Unmarshal.

Here is the handler that creates an item:

func handleCreateItem(w http.ResponseWriter, r *http.Request) {
    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
    }

    it, err := store.Add(input.Name, input.Quantity)
    if err != nil {
        fmt.Println("Save error:", err)
        writeError(w, http.StatusInternalServerError, "the item could not be saved")
        return
    }

    w.Header().Set("Location", fmt.Sprintf("/api/items/%d", it.ID))
    writeJSON(w, http.StatusCreated, it)
}

It has four steps, and each one can stop the request:

  1. Decode. A body that is too big gets status 413. Any other decoding problem gets 400, with the decoder's message, so the client can see what was wrong.
  2. Check. checkInput refuses an empty name, a name longer than 50 characters, and a quantity outside 1 to 1000. Decoding only says the JSON had the right shape. Whether the values make sense is up to you, as in Chapter 42.
  3. Save. A failure here is the server's fault, not the client's. The details go to the terminal, and the client gets a short message with status 500, as in Chapter 44.
  4. Reply. Status 201 Created, a Location header that says where the new item lives, and the item itself, now with its ID.

itemInput has no ID field. The server chooses IDs, so a body with "id" in it is an unknown field and is refused.

errors.As is new. errors.Is asks "is this error, or anything wrapped inside it, this value?". errors.As asks "is it, or anything inside it, of this type?", and if so, it fills your variable with it. http.MaxBytesReader gives an error of the type *http.MaxBytesError, which has a Limit field. So: declare a variable of that type, pass a pointer to it, and if errors.As returns true, the variable holds the error, and tooBig.Limit is 4096. When err is nil, errors.As simply returns false.

The delete handler uses readID, then store.Delete, and replies with w.WriteHeader(http.StatusNoContent): status 204, which means "it worked, and there is nothing to send back".

Status codes for an API

A browser shows a page, whatever its status. A program reads the status first, and decides what to do from it. So an API must choose its codes carefully:

Status Constant When this API sends it
200 OK http.StatusOK A GET worked.
201 Created http.StatusCreated A POST created an item.
204 No Content http.StatusNoContent A DELETE worked. There is no body.
400 Bad Request http.StatusBadRequest The body or the ID is wrong. Sending the same request again will not help.
404 Not Found http.StatusNotFound No item has that ID, or no route has that path.
405 Method Not Allowed The path exists, but not with this method. The router sends it.
413 Request Entity Too Large http.StatusRequestEntityTooLarge The body is over the limit.
500 Internal Server Error http.StatusInternalServerError Something failed on the server, such as saving.

The 4xx codes mean "you, the client, got something wrong". The 5xx codes mean "I, the server, failed". A client can try a 500 again later. A 400 will fail every time until the request changes.

Trying it with curl.exe

Start the server from its folder, since it reads and writes items.json in the folder it runs from:

cd exercises/45/03-items-api
go run .

Open a second terminal in VS Code, with the + in the terminal panel. It starts in go-work. The GET requests work as in Part 9:

curl.exe -i http://localhost:8080/api/items
HTTP/1.1 200 OK
Content-Type: application/json

[]

Sending JSON from PowerShell is harder. PowerShell changes the quotes inside an argument before curl.exe sees them, so -d '{"name": "Rice"}' can arrive as broken JSON. To avoid the problem, the bodies are in files, in exercises/45/requests/. -d "@file" tells curl.exe to send a file's content as the body. Keep the double quotes around it: in PowerShell, a word that starts with @ means something else. -H adds a header, here the Content-Type:

curl.exe -i -H "Content-Type: application/json" -d "@exercises/45/requests/rice.json" http://localhost:8080/api/items
HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/items/1

{
  "id": 1,
  "name": "Rice",
  "quantity": 2
}

rice.json holds {"name": "Rice", "quantity": 2}. Send tea.json and soap.json the same way, and they get the IDs 2 and 3. Then ask for the list, a search, and single items:

curl.exe "http://localhost:8080/api/items?q=tea"
[
  {
    "id": 2,
    "name": "Green tea",
    "quantity": 1
  }
]

curl.exe -i http://localhost:8080/api/items/99
HTTP/1.1 404 Not Found
Content-Type: application/json

{
  "error": "no item has the id 99"
}

curl.exe -i http://localhost:8080/api/items/abc
HTTP/1.1 400 Bad Request
Content-Type: application/json

{
  "error": "the id must be a whole number"
}

The other request files are bad on purpose. Each gets status 400 and a message:

File Body Error
empty-name.json {"name": " ", "quantity": 2} the name is empty
quantity-as-text.json {"name": "Rice", "quantity": "two"} invalid JSON: json: cannot unmarshal string into Go struct field itemInput.quantity of type int
unknown-field.json {"name": "Rice", "qty": 2} invalid JSON: json: unknown field \"qty\"

The \" in the last one is how JSON writes a " inside a string.

-X DELETE sends the DELETE method. Remove the soap, then try again:

curl.exe -i -X DELETE http://localhost:8080/api/items/3
HTTP/1.1 204 No Content

curl.exe -i -X DELETE http://localhost:8080/api/items/3
HTTP/1.1 404 Not Found
Content-Type: application/json

{
  "error": "no item has the id 3"
}

And a method that no route has:

curl.exe -i -X PUT http://localhost:8080/api/items
HTTP/1.1 405 Method Not Allowed
Allow: GET, HEAD, POST

Method Not Allowed

That body is plain text, not JSON, because the router wrote it, not your code. A client has to be ready for that. The next chapter is.

Stop the server with Ctrl+C, and start it again. Rice and green tea are still there, in items.json in the server's folder. The next new item gets the ID 4, not 3, because next_id was saved too. Leave the items in place: the next chapter uses them. Go back to go-work with cd ../../.. when you are done.

Write your own request file, milk.json, in exercises/45/requests/, and send it. Then try a quantity of 0, a name of 60 letters, and a body with "id": 5 in it. Which status and message does each one get?

Testing handlers with httptest

Trying every route with curl.exe after each change gets old fast. Chapter 34 tested functions with go test. A handler is a function too, but it needs a http.ResponseWriter and a *http.Request. The package net/http/httptest makes both, with no server and no network. This is the top of exercises/45/03-items-api/main_test.go:

// useTempStore gives the handlers an empty store in a temporary folder.
func useTempStore(t *testing.T) {
    s, err := openItemStore(filepath.Join(t.TempDir(), "items.json"))
    if err != nil {
        t.Fatalf("openItemStore: %v", err)
    }
    store = s
}

// send runs one request through the routes and returns what was written.
func send(method string, target string, body string) *httptest.ResponseRecorder {
    request := httptest.NewRequest(method, target, strings.NewReader(body))
    recorder := httptest.NewRecorder()
    routes().ServeHTTP(recorder, request)
    return recorder
}
  • httptest.NewRequest makes a request, as if a client had sent it. The body is a reader, so strings.NewReader turns a string into one.
  • httptest.NewRecorder makes a ResponseWriter that writes nothing to a network. It keeps what the handler wrote: Code holds the status, Header() the headers, and Body the body.
  • routes().ServeHTTP(recorder, request) passes the request to the router, which picks the handler from the method and path, exactly as the real server would. A wrong pattern is caught by the tests too.
  • useTempStore points the package-level store at a new, empty store in t.TempDir(), from Chapter 34. Each test starts with no items, and the real items.json is never touched.

With those two helpers, a test reads like a conversation:

func TestCreateThenGet(t *testing.T) {
    useTempStore(t)

    response := send("POST", "/api/items", `{"name": " Rice ", "quantity": 2}`)
    if response.Code != http.StatusCreated {
        t.Fatalf("POST status = %d, want %d; body %s", response.Code, http.StatusCreated, response.Body)
    }
    if got := response.Header().Get("Location"); got != "/api/items/1" {
        t.Errorf("Location = %q, want /api/items/1", got)
    }

    response = send("GET", "/api/items/1", "")
    if response.Code != http.StatusOK {
        t.Fatalf("GET status = %d, want %d", response.Code, http.StatusOK)
    }
    var got item
    err := json.Unmarshal(response.Body.Bytes(), &got)
    if err != nil {
        t.Fatalf("body is not an item: %v", err)
    }
    want := item{ID: 1, Name: "Rice", Quantity: 2}
    if got != want {
        t.Errorf("got %+v, want %+v", got, want)
    }
}

The test decodes the reply into an item and compares structs, instead of comparing text. That way, a change in spacing or field order does not break it. Two structs can be compared with == when all their fields can. The name " Rice " has spaces on purpose: the test also checks that the handler trims them.

Bad input is a table-driven test, with one subtest per body, as in Chapter 34:

tests := []struct {
    name string
    body string
    want int
}{
    {"not JSON", `hello`, http.StatusBadRequest},
    {"unknown field", `{"name": "Rice", "quantity": 2, "colour": "white"}`, http.StatusBadRequest},
    {"empty name", `{"name": "  ", "quantity": 2}`, http.StatusBadRequest},
    {"no quantity", `{"name": "Rice"}`, http.StatusBadRequest},
    {"two objects", `{"name": "Rice", "quantity": 2} {}`, http.StatusBadRequest},
    {"too big", `{"name": "` + strings.Repeat("a", 5000) + `"}`, http.StatusRequestEntityTooLarge},
}

Each subtest sends its body, checks the status, and checks that store.All() is still empty: a bad request must not add anything. The other tests check an empty list, a bad and a missing ID, deleting twice, and that items survive opening the file a second time.

Run them from the server's folder:

cd exercises/45/03-items-api
go test -v

The output starts like this, and ends with the line that counts:

=== RUN   TestListEmpty
--- PASS: TestListEmpty (0.00s)
=== RUN   TestCreateThenGet
--- PASS: TestCreateThenGet (0.00s)
=== RUN   TestCreateRejectsBadInput
=== RUN   TestCreateRejectsBadInput/not_JSON
...
PASS
ok      itemsapi        0.215s

The times differ from run to run. Go writes the spaces in a subtest's name as _.

The tests replace the package-level store, which is fine because they run one after another. A test that called t.Parallel() could not share it like this. For a small server, one package-level variable set up by main is fine.

Break the server on purpose: in handleCreateItem, change http.StatusCreated to http.StatusOK, and run go test. Then change the route "DELETE /api/items/{id}" to "DELETE /api/item/{id}". Which tests fail, and what do they say? Put both back.

Homework

Homework starters are in exercises/45/homework/. Each one runs as it is, with a placeholder. Problem 3 and the challenge are folders with their own go.mod, so cd into the folder and use go run . and go test -v.

Problem 1 — A quotes API

Open exercises/45/homework/01-quotes-api.go. Add struct tags so that the JSON names are id, text and author. Write writeJSON and writeError as in the chapter. Then write the handlers: GET /api/quotes replies with every quote, and GET /api/quotes/{id} with one, or with status 400 for an ID that is not a whole number and 404 for an ID with no quote.

Problem 2 — A temperature API

Open exercises/45/homework/02-convert-api.go. POST /api/convert takes {"celsius": 21.5} and replies with {"celsius": 21.5, "fahrenheit": 70.7}, rounded to one decimal place. Decode strictly, with a limit of 1024 bytes. Reply with 400 and an error for bad JSON, a missing celsius, and a temperature below -273.15. A *float64 field is nil when the field is missing, which tells "missing" apart from 0.

Problem 3 — Test a counter API

Open the folder exercises/45/homework/03-test-counter. The server is finished. In main_test.go, write the three tests: the counter starts at 0, adding 5 and then 3 gives 8, and a table of bad bodies each get status 400 and leave the counter at 0.

Challenge — Update an item

Open the folder exercises/45/homework/04-update-items, a copy of the chapter's API. Add PUT /api/items/{id}, which replaces the name and quantity of an item. The body is the same as for POST, and is checked the same way. Reply with 200 and the updated item, 400 for a bad ID or body, and 404 for an ID with no item. Write the store's Update method, then the handler, then TestUpdate.

Stuck or done? Open the homework solutions page.