A JSON API by hand

A JSON API is a mux, a handler per route, a struct per request and per response, and a status code for each answer. The standard library has all of it. The programs below run the server and the client in one process with httptest.NewServer, so each one shows the requests and the exact answers a caller receives.

A POST and a GET

The API keeps the notes in a map behind a mutex, because the server runs every request in its own goroutine. The create handler decodes the body, checks the title, assigns an id and answers 201 with the stored note; the get handler reads the path value and answers 200 or 404. The client posts two notes and asks for one that exists and one that does not.

package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "strconv" "sync" ) type Note struct { ID int `json:"id"` Title string `json:"title"` } type API struct { mu sync.Mutex notes map[int]Note nextID int } func (a *API) create(w http.ResponseWriter, r *http.Request) { var note Note if err := json.NewDecoder(r.Body).Decode(&note); err != nil { http.Error(w, `{"error":"invalid JSON"}`, http.StatusBadRequest) return } if note.Title == "" { http.Error(w, `{"error":"title is required"}`, http.StatusBadRequest) return } a.mu.Lock() note.ID = a.nextID a.nextID++ a.notes[note.ID] = note a.mu.Unlock() w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(note) } func (a *API) get(w http.ResponseWriter, r *http.Request) { id, err := strconv.Atoi(r.PathValue("id")) if err != nil { http.Error(w, `{"error":"bad id"}`, http.StatusBadRequest) return } a.mu.Lock() note, ok := a.notes[id] a.mu.Unlock() if !ok { http.Error(w, `{"error":"note not found"}`, http.StatusNotFound) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(note) } func main() { api := &API{notes: map[int]Note{}, nextID: 1} mux := http.NewServeMux() mux.HandleFunc("POST /notes", api.create) mux.HandleFunc("GET /notes/{id}", api.get) srv := httptest.NewServer(mux) defer srv.Close() post := func(body string) { resp, err := http.Post(srv.URL+"/notes", "application/json", bytes.NewBufferString(body)) if err != nil { panic(err) } data, _ := io.ReadAll(resp.Body) resp.Body.Close() fmt.Printf("POST %d %s", resp.StatusCode, data) } post(`{"title":"buy milk"}`) post(`{"title":"write lesson"}`) for _, path := range []string{"/notes/1", "/notes/9"} { resp, err := http.Get(srv.URL + path) if err != nil { panic(err) } data, _ := io.ReadAll(resp.Body) resp.Body.Close() fmt.Printf("GET %s %d %s", path, resp.StatusCode, data) } }

go build -o app main.go && ./app

POST 201 {"id":1,"title":"buy milk"}
POST 201 {"id":2,"title":"write lesson"}
GET /notes/1 200 {"id":1,"title":"buy milk"}
GET /notes/9 404 {"error":"note not found"}

The ids are assigned in the order the requests arrived, and the body of each answer is one JSON object with a newline. The map is guarded by a mutex because two creates can run at once; a store with a database transaction would not need it, which is what the capstone service does.

The content type

A handler that reads JSON should refuse a body announced as something else, and 415 is the status for that. The check is on the media type without its parameters, so application/json; charset=utf-8 is accepted and text/plain is not. The answer below is a JSON error with the matching status.

package main import ( "bytes" "fmt" "io" "net/http" "net/http/httptest" ) func main() { mux := http.NewServeMux() mux.HandleFunc("POST /notes", func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Content-Type") != "application/json" { w.WriteHeader(http.StatusUnsupportedMediaType) fmt.Fprintln(w, `{"error":"expected application/json"}`) return } fmt.Fprintln(w, `{"ok":true}`) }) srv := httptest.NewServer(mux) defer srv.Close() resp, err := http.Post(srv.URL+"/notes", "text/plain", bytes.NewBufferString("hi")) if err != nil { panic(err) } body, _ := io.ReadAll(resp.Body) resp.Body.Close() fmt.Printf("%d %s", resp.StatusCode, body) }

go build -o app main.go && ./app

415 {"error":"expected application/json"}

The error is JSON and the status is 415, so a client parses the body the same way it parses a success. A real check uses mime.ParseMediaType and compares the type, because a charset parameter is legal and common; the string comparison above is short enough to show the idea.

Validation

A decoded field is not a valid one. The handler checks the title after the decode, answers 400 with a message a client can show, and stores nothing. The same shape covers a length limit, a number range and a field that must be one of a list; the check belongs in the handler, next to the rule it enforces.

package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "net/http/httptest" ) type Note struct { Title string `json:"title"` } func main() { mux := http.NewServeMux() mux.HandleFunc("POST /notes", func(w http.ResponseWriter, r *http.Request) { var note Note if err := json.NewDecoder(r.Body).Decode(&note); err != nil { http.Error(w, `{"error":"invalid JSON"}`, http.StatusBadRequest) return } if note.Title == "" { http.Error(w, `{"error":"title is required"}`, http.StatusBadRequest) return } w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(note) }) srv := httptest.NewServer(mux) defer srv.Close() resp, err := http.Post(srv.URL+"/notes", "application/json", bytes.NewBufferString(`{"title":""}`)) if err != nil { panic(err) } body, _ := io.ReadAll(resp.Body) resp.Body.Close() fmt.Printf("%d %s", resp.StatusCode, body) }

go build -o app main.go && ./app

400 {"error":"title is required"}

An empty title is a client mistake, not a server failure, so the status is 400 and not 500. A handler that returns a list of problems instead of one message is friendlier for a form; the single message is enough for a first API and the shape stays the same.

A body that is not JSON

A truncated body fails in the decoder before any field is checked, and the handler turns that into a 400 with a message that does not repeat the parser's internal text. The status is the contract; the message is for a human, and the log line is where the offset belongs.

package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "net/http/httptest" ) func main() { mux := http.NewServeMux() mux.HandleFunc("POST /notes", func(w http.ResponseWriter, r *http.Request) { var body map[string]any if err := json.NewDecoder(r.Body).Decode(&body); err != nil { w.WriteHeader(http.StatusBadRequest) fmt.Fprintln(w, `{"error":"invalid JSON"}`) return } fmt.Fprintln(w, `{"ok":true}`) }) srv := httptest.NewServer(mux) defer srv.Close() resp, err := http.Post(srv.URL+"/notes", "application/json", bytes.NewBufferString(`{"title":`)) if err != nil { panic(err) } body, _ := io.ReadAll(resp.Body) resp.Body.Close() fmt.Printf("%d %s", resp.StatusCode, body) }

go build -o app main.go && ./app

400 {"error":"invalid JSON"}

The body was {"title": and the decoder reported an unexpected end. The client gets one sentence and a status, and the handler logs the parser error with the request id, which is the line an operator needs when a client's serializer is broken.

The shape of an error

One error shape for the whole API is worth more than a clever one: {"error": "..."} with the status that matches. http.Error writes that body but sets text/plain, so a client that parses every answer as JSON breaks on the errors. The capstone service sets Content-Type: application/json before writing, encodes an error struct and keeps the helper in one function.

The rest of the contract: a 201 with the created object and no Location unless the client needs one, a 200 with the object for a get, a 404 with the error, a 405 from the mux, a 415 for the wrong media type and a 500 only for a bug. A client that sees a 500 knows to retry a GET and not a POST, which is the reason the statuses are worth getting right.

Exercises

  1. Add a GET /notes that returns a JSON array of every note, sorted by id. Which parts of the handler do you reuse, and which are new?
  2. Change the media type check to mime.ParseMediaType and post with application/json; charset=utf-8. What did the string comparison do, and what does the parser do?
  3. Return a 400 with two problems in one JSON object and read it in the client. What shape would a form need, and what shape would a script need?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What status does a create answer?

    Answer

    201 Created

    The body carries the created object.

  2. What status is a missing note?

    Answer

    404

    The path names a resource that does not exist.

  3. What status is the wrong content type?

    Answer

    415

    Unsupported Media Type.

  4. What status is an empty required field?

    Answer

    400

    The client sent an invalid body.

  5. Why is a mutex needed around the map?

    Answer

    The server runs requests in several goroutines

    A plain map races under concurrent writes.

  6. What does http.Error set that a JSON client dislikes?

    Answer

    A text/plain content type

    Set application/json before writing.

  7. What does json.NewDecoder(r.Body).Decode do?

    Answer

    Reads one JSON value from the request body

    The body is a stream and is read once.

  8. What should an API do with a parser error?

    Answer

    Answer 400 and log the details

    The client gets a sentence, the log gets the offset.

  9. Which status does a client retry a GET on?

    Answer

    500, and not a POST without an idempotency key

    A retried POST can create a duplicate.

  10. Why one error shape for the API?

    Answer

    A client parses every answer, success or error, the same way

    Consistency is the feature.

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

Banner image