Thuta Learning
Go
AdvancedProgrammingBeginner

HTTP & JSON API Fundamentals

GoLesson 2435 min

What you'll walk away with

  • Register method-and-wildcard patterns such as "GET /tasks/{id}" on http.ServeMux and read them with r.PathValue
  • Decode a request body into a struct with json.NewDecoder and reject bad input with 400
  • Write a writeJSON helper that sets the header, status code and body in the right order
  • Exercise handlers in-process with httptest.NewServer and httptest.NewRecorder

Explain it simply

A JSON API in plain language

A JSON API works like a restaurant counter. The client hands over an order slip, the HTTP request: what to do (GET, POST), which thing (/tasks/1) and, when needed, the details (a JSON body). The server hands back an answer, the response: a status code that says how it went, plus a JSON body.

Go needs no framework for this. net/http connects routes to handler functions, and encoding/json converts between Go structs and JSON. The httptest package lets you try the whole server inside one program, without the internet.

Problem → Why → Solution

The problem: a handler that only seems to work

This handler returns a task when you try it in a browser. Then the mobile team starts filing reports: asking for a missing task returns status 200 with an empty object, a DELETE is answered like a GET, and when JSON parsing fails the client cannot tell what went wrong. The response does not even say Content-Type: application/json.

handler_bad.go
var tasks = map[string]Task{} // shared by every request, no lock

func taskHandler(w http.ResponseWriter, r *http.Request) {
    id := strings.TrimPrefix(r.URL.Path, "/tasks/") // any method lands here
    task := tasks[id]                                // missing id -> zero Task
    data, _ := json.Marshal(task)                    // error ignored
    w.Write(data)                                    // always 200, no Content-Type
}

Why this matters for an API

The caller of an API is a program, not a person, and it decides what to do from the status code and the shape of the body. Return 200 instead of 404 and the client will display the empty task as real data. Method, status code, Content-Type and error body form a contract between client and server, and every handler has to keep it.

Core concept: route, decode, respond

In net/http a handler is a function with the signature func(w http.ResponseWriter, r *http.Request). r carries everything the client sent (method, URL, headers, body), and w is where you write the response. http.ServeMux is the router: it matches each request against registered patterns and calls the matching handler. Since Go 1.22, patterns can include a method and wildcards: "GET /tasks/{id}" accepts only GET (and HEAD) requests, and r.PathValue("id") returns the text in the {id} slot. When the path matches but the method does not, the mux itself answers 405 Method Not Allowed.

To read a JSON body, use json.NewDecoder(r.Body).Decode(&v). Decode matches JSON keys to the json tags on struct fields and fills only exported (capitalised) fields. It returns an error for malformed JSON, but a missing field is not an error; it simply stays at its zero value. So after decoding you must check business rules yourself, such as whether the title is empty.

The order of writing a response matters: headers first with w.Header().Set(...), then w.WriteHeader(status), then the body. Once the body is written, the headers and status have already gone to the client and can no longer change. If you write a body without calling WriteHeader, 200 is used automatically. Putting this sequence in a helper like writeJSON makes every handler follow it.

When two patterns both match a request, the more specific one wins: GET /tasks/new is more specific than GET /tasks/{id}, so /tasks/new goes to the first handler. Registering two patterns that conflict without either being more specific makes ServeMux panic at registration time, so you find the mistake the moment the server starts.

StatusReturn it when
200 OKthe requested data is returned
201 Createda POST created a new resource
400 Bad Requestthe JSON or a path value is malformed
404 Not Foundno resource has that ID
405 Method Not Allowedthe path exists but not for that method (the mux sends it)
The journey of one request
  1. Mux matches method and path
  2. Handler reads path value and body
  3. Validate; on error answer 4xx
  4. Write header, status, then JSON

Return right after writing an error response; otherwise the handler keeps running and appends a success body too.

General pattern

go
mux := http.NewServeMux()
mux.HandleFunc("METHOD /resource/{name}", handler)

func handler(w http.ResponseWriter, r *http.Request) {
    value := r.PathValue("name")
    var in InputType
    if err := json.NewDecoder(r.Body).Decode(&in); err != nil { /* 400 */ return }
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(statusCode)
    json.NewEncoder(w).Encode(result)
}

The pattern declares method, path and wildcards in one string. Inside the handler, read the path value and body, validate them, then write header, status and body in that order.

Worked example: a task API and six requests

The program below has two routes: POST /tasks creates a task, and GET /tasks/{id} looks one up. httptest.NewServer starts a real HTTP server on a local test port, and main sends six requests with srv.Client(): two successes and four error cases. Each output line shows the request, the status code and the response body.

task_api.go
package main

import (
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "net/http/httptest"
    "strconv"
    "strings"
    "sync"
)

type Task struct {
    ID    int    `json:"id"`
    Title string `json:"title"`
    Done  bool   `json:"done"`
}

type TaskStore struct {
    mu     sync.Mutex
    nextID int
    tasks  map[int]Task
}

func writeJSON(w http.ResponseWriter, status int, v any) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(status)
    json.NewEncoder(w).Encode(v)
}

func (s *TaskStore) create(w http.ResponseWriter, r *http.Request) {
    var in struct {
        Title string `json:"title"`
    }
    if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Title == "" {
        writeJSON(w, http.StatusBadRequest,
            map[string]string{"error": "title is required"})
        return
    }
    s.mu.Lock()
    s.nextID++
    task := Task{ID: s.nextID, Title: in.Title}
    s.tasks[task.ID] = task
    s.mu.Unlock()
    writeJSON(w, http.StatusCreated, task)
}

func (s *TaskStore) get(w http.ResponseWriter, r *http.Request) {
    id, err := strconv.Atoi(r.PathValue("id"))
    if err != nil {
        writeJSON(w, http.StatusBadRequest,
            map[string]string{"error": "id must be a number"})
        return
    }
    s.mu.Lock()
    task, ok := s.tasks[id]
    s.mu.Unlock()
    if !ok {
        writeJSON(w, http.StatusNotFound, map[string]string{"error": "task not found"})
        return
    }
    writeJSON(w, http.StatusOK, task)
}

func main() {
    store := &TaskStore{tasks: map[int]Task{}}
    mux := http.NewServeMux()
    mux.HandleFunc("POST /tasks", store.create)
    mux.HandleFunc("GET /tasks/{id}", store.get)

    srv := httptest.NewServer(mux) // real HTTP server on a local test port
    defer srv.Close()

    call := func(method, path, body string) {
        req, _ := http.NewRequest(method, srv.URL+path, strings.NewReader(body))
        res, err := srv.Client().Do(req)
        if err != nil {
            fmt.Println("request failed:", err)
            return
        }
        defer res.Body.Close()
        data, _ := io.ReadAll(res.Body)
        fmt.Printf("%s %s -> %d %s", method, path, res.StatusCode, data)
    }

    call("POST", "/tasks", `{"title":"write tests"}`)
    call("GET", "/tasks/1", "")
    call("GET", "/tasks/42", "")
    call("GET", "/tasks/abc", "")
    call("POST", "/tasks", `{"title":""}`)
    call("DELETE", "/tasks/1", "")
}

Code breakdown

  1. Method + wildcard routesmux.HandleFunc("GET /tasks/{id}", store.get)

    The pattern accepts only GET, and {id} captures one path segment. DELETE /tasks/1 matches the path but not the method, so the mux answers 405, as the last output line shows.

  2. One response helperw.WriteHeader(status)

    writeJSON sets Content-Type first, writes the status next and encodes the body last. Every handler goes through it, so the order can never be wrong.

  3. Decode and validateif err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Title == "" {

    Both malformed JSON and an empty title are rejected with 400. {"title":""} is valid JSON but breaks the business rule, which is why the second check is needed.

  4. Read the wildcardid, err := strconv.Atoi(r.PathValue("id"))

    PathValue returns a string, so it is converted to a number. An ID that cannot be converted, like /tasks/abc, gets 400, while a well-formed ID that does not exist gets 404.

  5. In-process serversrv := httptest.NewServer(mux) // real HTTP server on a local test port

    NewServer starts a real server on the loopback address, so routing, headers and status codes behave exactly as in production. defer srv.Close() shuts it down when main returns.

You should see
POST /tasks -> 201 {"id":1,"title":"write tests","done":false}
GET /tasks/1 -> 200 {"id":1,"title":"write tests","done":false}
GET /tasks/42 -> 404 {"error":"task not found"}
GET /tasks/abc -> 400 {"error":"id must be a number"}
POST /tasks -> 400 {"error":"title is required"}
DELETE /tasks/1 -> 405 Method Not Allowed

Running it for real and limiting input

httptest is for trying things out. To serve for real, put the same mux into an http.Server and set timeouts. Calling http.ListenAndServe directly has no timeouts, so slow clients can hold connections open for a long time. You can also cap the body size with http.MaxBytesReader and reject unexpected fields with DisallowUnknownFields.

go
srv := &http.Server{
    Addr:              ":8080",
    Handler:           mux,
    ReadHeaderTimeout: 5 * time.Second,
    ReadTimeout:       10 * time.Second,
    WriteTimeout:      10 * time.Second,
}
log.Fatal(srv.ListenAndServe())

// inside a handler that accepts a body:
r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // at most 1 MiB
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields() // {"titel": "..."} becomes an error

Handlers run concurrently

net/http calls each request on its own goroutine. That is why TaskStore in the example has a sync.Mutex: two handlers can touch nextID and the map at the same moment.

In real projects

In real projects

Plenty of production APIs run on Go's standard library alone. Since ServeMux gained methods and wildcards in Go 1.22, many projects no longer need a separate router library. Teams typically reuse the patterns from this lesson like this:

  • Every error response uses one shape, {"error": "..."}, so the frontend shows messages from one place.
  • Handlers are methods on a struct like TaskStore, and dependencies such as a database connection or logger come in through its fields.
  • Each handler test uses httptest.NewRecorder or httptest.NewServer, so CI never needs a public network port.
  • Logging, authentication and panic recovery are added as middleware functions that wrap an http.Handler.
  • Paths carry a version, such as /v1/tasks, so older mobile apps keep working; a breaking change to the response shape goes into a new /v2 route.

Common mistakes

Common HTTP handler mistakes

Forgetting return after writing an error

Calling http.Error(w, ...) or writeJSON(w, 400, ...) without return lets the handler keep going and write the success body too. The client receives two JSON values glued together, and the log shows a 'superfluous response.WriteHeader call' warning.

Setting headers after WriteHeader or Write

Calling w.Header().Set("Content-Type", ...) after w.WriteHeader(201) changes nothing, because the headers have already been sent, and no error is reported. Always set headers first.

Unexported fields and wrong JSON tags

With type Task struct { title string }, encoding/json cannot see title, so responses come out as {} and decoding never fills it. Start the field with a capital letter and add a json:"title" tag. A misspelled tag leaves the field at its zero value, so keep validation in place to catch it.

Best practices

Best practices

  • Keep the header-status-body order in one helper such as writeJSON.
  • Always put the method in the pattern so the mux rejects unsupported methods with 405.
  • Set http.Server timeouts and MaxBytesReader on real servers.
  • Write one httptest case per status code, especially the error paths.

Mini challenge

Mini challenge: a scoreboard API

Write a small API that adds up player scores. POST /scores accepts {"player":"ada","points":5} and increases that player's total. GET /scores/{player} returns the total. Test it without opening a port by calling mux.ServeHTTP directly with httptest.NewRecorder.

  • Register both routes with method-and-wildcard patterns
  • Reject malformed JSON or unknown fields with 400, and an empty player or points <= 0 with 422
  • Answer 404 for a player with no scores
  • Guard the map with a mutex and print the status and body of six requests
scoreboard.go
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "net/http/httptest"
    "strings"
    "sync"
)

type Scoreboard struct {
    mu     sync.Mutex
    points map[string]int
}

type scoreInput struct {
    // TODO: Player and Points fields with json tags
}

func (b *Scoreboard) addScore(w http.ResponseWriter, r *http.Request) {
    // TODO: decode with DisallowUnknownFields, validate, add, respond
}

func (b *Scoreboard) getScore(w http.ResponseWriter, r *http.Request) {
    // TODO: read r.PathValue("player"), answer 200 or 404
}

func main() {
    board := &Scoreboard{points: map[string]int{}}
    mux := http.NewServeMux()
    // TODO: register "POST /scores" and "GET /scores/{player}"

    // TODO: send requests with httptest.NewRecorder + mux.ServeHTTP
    _ = board
    fmt.Println("todo")
}

Expected: After adding 5 and 3 for ada, GET /scores/ada returns 200 {"player":"ada","total":8}. bob gets 404, points -2 gets 422, and an unknown field such as "pts" gets 400.

Show hint

Create rec := httptest.NewRecorder(), then call mux.ServeHTTP(rec, httptest.NewRequest(method, target, strings.NewReader(body))). Read the result from rec.Code and rec.Body.String(). Read the new total while you still hold the lock.

Show solution
scoreboard.go
package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "net/http/httptest"
    "strings"
    "sync"
)

type Scoreboard struct {
    mu     sync.Mutex
    points map[string]int
}

type scoreInput struct {
    Player string `json:"player"`
    Points int    `json:"points"`
}

func respond(w http.ResponseWriter, status int, v any) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(status)
    json.NewEncoder(w).Encode(v)
}

func (b *Scoreboard) addScore(w http.ResponseWriter, r *http.Request) {
    var in scoreInput
    dec := json.NewDecoder(r.Body)
    dec.DisallowUnknownFields()
    if err := dec.Decode(&in); err != nil {
        respond(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON body"})
        return
    }
    if in.Player == "" || in.Points <= 0 {
        respond(w, http.StatusUnprocessableEntity,
            map[string]string{"error": "player and positive points are required"})
        return
    }
    b.mu.Lock()
    b.points[in.Player] += in.Points
    total := b.points[in.Player]
    b.mu.Unlock()
    respond(w, http.StatusOK, map[string]any{"player": in.Player, "total": total})
}

func (b *Scoreboard) getScore(w http.ResponseWriter, r *http.Request) {
    player := r.PathValue("player")
    b.mu.Lock()
    total, ok := b.points[player]
    b.mu.Unlock()
    if !ok {
        respond(w, http.StatusNotFound, map[string]string{"error": "unknown player"})
        return
    }
    respond(w, http.StatusOK, map[string]any{"player": player, "total": total})
}

func main() {
    board := &Scoreboard{points: map[string]int{}}
    mux := http.NewServeMux()
    mux.HandleFunc("POST /scores", board.addScore)
    mux.HandleFunc("GET /scores/{player}", board.getScore)

    send := func(method, target, body string) {
        rec := httptest.NewRecorder()
        mux.ServeHTTP(rec, httptest.NewRequest(method, target, strings.NewReader(body)))
        fmt.Printf("%-4s %-14s %d %s", method, target, rec.Code, rec.Body.String())
    }

    send("POST", "/scores", `{"player":"ada","points":5}`)
    send("POST", "/scores", `{"player":"ada","points":3}`)
    send("GET", "/scores/ada", "")
    send("GET", "/scores/bob", "")
    send("POST", "/scores", `{"player":"bob","points":-2}`)
    send("POST", "/scores", `{"player":"bob","pts":2}`)
}

Quick quiz 1 / 3

Only mux.HandleFunc("GET /tasks/{id}", get) is registered. What happens when a client sends DELETE /tasks/7?

Quick quiz 2 / 3

A handler calls w.WriteHeader(http.StatusCreated) and then w.Header().Set("Content-Type", "application/json"). What does the client get?

Quick quiz 3 / 3

The body {"title": "buy milk"} is decoded into var in struct{ title string }. What is the result?

What to remember

  • Go 1.22+ ServeMux patterns carry a method and {wildcards}, read with r.PathValue.
  • After decoding with json.NewDecoder, check business rules yourself and return a 4xx (and return from the handler) on failure.
  • Write a response as header, status, body, ideally through one helper.
  • httptest.NewServer and httptest.NewRecorder let you exercise an API inside the program, with no network.

Package net/http — Go Packages

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.