Capstone 3: the API and its layout
The third capstone is a notes web service: a Go process that serves a JSON API and, in production, the built frontend from the same binary. It uses the standard library only. This lesson fixes the contract before any handler is written: the routes, the shapes and the packages that own each part.
The routes
Five routes under /api/notes and a health route. The method is part of the pattern, so the mux answers 405 for a method that is not registered, and r.PathValue("id") reads the id. The routes are registered in one function, Routes, which is also where the middleware chain is applied, so a test gets the same handler the server uses.
// Package api is the HTTP layer of the notes service.
package api
import (
"log/slog"
"net/http"
"example.com/notesapi/internal/store"
)
// API holds the store and the logger the handlers use.
type API struct {
store store.Store
log *slog.Logger
}
// New returns an API over the given store.
func New(st store.Store, log *slog.Logger) *API {
return &API{store: st, log: log}
}
// Routes returns the mux with the middleware chain around it.
func (a *API) Routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", a.health)
mux.HandleFunc("GET /api/notes", a.list)
mux.HandleFunc("POST /api/notes", a.create)
mux.HandleFunc("GET /api/notes/{id}", a.get)
mux.HandleFunc("PUT /api/notes/{id}", a.update)
mux.HandleFunc("DELETE /api/notes/{id}", a.delete)
return a.recoverer(a.requestID(a.logging(mux)))
}
The API struct holds the two dependencies a handler may use: the store and the logger. That is the whole wiring, and the constructor is the only place that knows both. A handler never reaches a global, which is what makes the tests in lesson 133 possible.
The shapes
A note is an id, a title and a done flag. An error is {"error": "..."} with the status that matches, which is the one shape every route shares. A list is a JSON array, a create answers 201 with the note, a delete answers 204 with no body, and a missing note is 404 with the error shape.
package store
import "errors"
// ErrNotFound is returned for an id that does not exist.
var ErrNotFound = errors.New("note not found")
// ErrEmptyTitle is returned for a note with no title.
var ErrEmptyTitle = errors.New("title is required")
// Note is one note of the service.
type Note struct {
ID int `json:"id"`
Title string `json:"title"`
Done bool `json:"done"`
}
// Store is what the API needs from its storage.
type Store interface {
List() ([]Note, error)
Get(id int) (Note, error)
Create(title string) (Note, error)
Update(id int, title string, done bool) (Note, error)
Delete(id int) error
}
The store interface is here, next to the model, and the API imports it. The interface is the seam the fake store replaces in the tests; the memory and file implementations arrive in the next lesson.
The packages
Three packages and a command. internal/store owns the data and the rules of a note, internal/api owns HTTP, and cmd/server owns configuration, the listener and the shutdown. internal/web will own the embedded frontend in lesson 134. Nothing under internal/ is importable by another module, which is the layout rule from lesson 60 applied to a service.
The dependency graph is a line: the command imports the API and the store, the API imports the store, and the store imports nothing of the project. A change to the JSON shape touches the store and the API, and a change to the listener touches only the command.
A first request
The demo starts the API with a memory store, mounts it under /api/ and /healthz, and makes four requests. The output is the contract in action: the health JSON, two created notes and the list.
package main
import (
"bytes"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"example.com/notesapi/internal/api"
"example.com/notesapi/internal/store"
)
func main() {
a := api.New(store.NewMemory(), slog.New(slog.NewTextHandler(io.Discard, nil)))
handler := a.Routes()
root := http.NewServeMux()
root.Handle("/api/", handler)
root.Handle("/healthz", handler)
srv := httptest.NewServer(root)
defer srv.Close()
get := func(method, path, body string) {
req, err := http.NewRequest(method, srv.URL+path, bytes.NewBufferString(body))
if err != nil {
panic(err)
}
if body != "" {
req.Header.Set("Content-Type", "application/json")
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
data, _ := io.ReadAll(resp.Body)
resp.Body.Close()
fmt.Printf("%-6s %-12s %d %s", method, path, resp.StatusCode, data)
}
get("GET", "/healthz", "")
get("POST", "/api/notes", `{"title":"buy milk"}`)
go run ./cmd/l129
GET /healthz 200 {"status":"ok"}
POST /api/notes 201 {"id":1,"title":"buy milk","done":false}
POST /api/notes 201 {"id":2,"title":"write lesson","done":false}
GET /api/notes 200 [{"id":1,"title":"buy milk","done":false},{"id":2,"title":"write lesson","done":false}]
The create answered 201 with the stored note including the id the store assigned, and the list returned an array in id order. The two requests without a Content-Type header worked because the create handler does not require one; the page of lesson 97 made the case for requiring it, and a public API should.
An API is a contract
The contract is the routes, the shapes and the statuses, and it is written down before the code so a client can be written against it. Three rules keep it honest: one error shape everywhere, the status that matches the cause, and the id in the path rather than in a body. The next lesson gives the service a store that survives a restart.
Exercises
- Add a /api/notes/{id}/done route that toggles a note. Which layer does the toggle belong to, and what status does it answer?
- Decide the status for a create with an empty title and for a note that does not exist. Which routes share the error shape, and what does a client branch on?
- Draw the import graph of the three packages. Which package would a second command share, and which one would it not?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Where are the routes registered?
Answer
In one Routes function that also applies the middleware
A test gets the same handler.
-
What does the method in a pattern give?
Answer
A 405 for a method that is not registered
The mux checks it.
-
What is the error shape?
Answer
An object with one error key
Every route shares it.
-
What does a create answer?
Answer
201 with the stored note
The id is in the body.
-
What does a delete answer?
Answer
204 with no body
The note is gone.
-
Which package owns the listener?
Answer
cmd/server
The command owns configuration and shutdown.
-
Which package owns HTTP?
Answer
internal/api
The store knows nothing of HTTP.
-
Why is the store an interface?
Answer
A fake replaces it in the tests
It is the seam of the service.
-
Which import does the store have from the project?
Answer
None
The graph is a line.
-
Why fix the contract before the handlers?
Answer
A client can be written against it
The contract is the product.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev