1. Contract and response format
When you write a list endpoint, it may seem that you just need to return an array. But list responses are exactly the kind of thing that start to live their own lives: scripts parse them, automated tests depend on them, people compare them as JSON for equality, and users complain if items “jump” around. That is why the list contract is not only about the id/title/done fields, but also about ordering rules and filter behavior.
We fix the following contract for GET /api/v1/tasks:
- Method and path: GET /api/v1/tasks
- Query parameters:
- done=true|false — optional status filter
- sort=id|title — optional sorting
- Response: 200 OK and a JSON object of the form { "tasks": [...] }, not a “bare array”, so the format can be extended without changing the response type (for example, by adding "total").
Why do we talk separately about “stability”? Because even seemingly “simple” things like sorting can produce different orders for equal elements when the implementation changes. This is one of the reasons tests that depend on order suddenly break.
To avoid turning clients into archaeologists, we make the output deterministic in advance.
DTO and response wrapper
Before filtering and sorting, it is important to agree on the shape of the outgoing data. In the HTTP layer we usually work with DTOs (data transfer objects) — structures that reflect the API contract and are not required to match the domain model 100% . That is normal: the domain is about rules, HTTP is about packaging.
Minimal DTO and response wrapper:
type TaskDTO struct {
ID int `json:"id"`
Title string `json:"title"`
Done bool `json:"done"`
}
type ListTasksResponse struct {
Tasks []TaskDTO `json:"tasks"`
}
Why { "tasks": [...] }, and not just []TaskDTO? Because an API rarely stays “just a list”. If you later want to add total, next_page, generated_at — you will not have a painful format change where clients must rewrite the parser from “array → object”.
And yes, this is one of those cases where an extra 10 bytes of JSON are a justified investment in a calm life.
2. Query params: reading and processing
Query parameters look harmless because they are “just strings”. But in practice they are the same kind of user input as JSON body or {id} in the path: they can be empty, duplicated, unexpected, and all of that must be handled consistently. If we “accept everything as is”, bugs will not show up immediately, but later — when a client accidentally sends ?done=tru and gets strange behavior.
In practice, r.URL.Query() returns url.Values, that is map[string][]string.
import "net/http"
func readQuery(r *http.Request) map[string][]string {
q := r.URL.Query()
return q
}
And here the first subtlety appears: one key can be passed multiple times, for example ?sort=id&sort=title. For teaching purposes, we choose a strict policy: if a parameter is specified more than once, it is a validation error (400), because otherwise it is hard for the client to predict the result.
Exactly one value for a parameter
Let's make a small helper to “take exactly one value”:
import (
"fmt"
"net/url"
)
func getSingleQuery(q url.Values, key string) (string, bool, error) {
vals, ok := q[key]
if !ok {
return "", false, nil
}
if len(vals) != 1 {
return "", true, fmt.Errorf("query %q must be single", key)
}
return vals[0], true, nil
}
Here, present (the second result) matters more than it seems. It helps distinguish “the parameter is absent” from “the parameter is present, but empty/broken”. For done this is critical.
done filter: three states instead of one bool
There is a typical beginner trap in filters: you want to read done as a bool and be done with it. But done in the query actually has three states, and they are semantically different:
- the parameter is absent → do not apply the filter
- the parameter is present and valid (true/false) → apply the filter
- the parameter is present, but invalid → this is 400 (validation)
If you do not distinguish between (1) and (2), you get a bug: “parameter absent” behaves the same as done=false, and the client suddenly sees only unfinished tasks.
Let's build a parser for an optional bool:
import (
"net/url"
"strconv"
)
func parseOptionalBool(q url.Values, key string) (value bool, present bool, err error) {
raw, present, err := getSingleQuery(q, key)
if err != nil || !present {
return false, present, err
}
if raw == "" {
return false, true, strconv.ErrSyntax
}
v, err := strconv.ParseBool(raw)
if err != nil {
return false, true, err
}
return v, true, nil
}
Now filtering. We want to do it as simply as possible and without extra allocations. The “in-place filtering” pattern looks like this: take dst := tasks[:0] and append matching elements. It sounds like magic, but in fact it is just a neat reuse of the array under the slice.
func filterByDone(tasks []TaskDTO, done bool) []TaskDTO {
dst := tasks[:0]
for _, t := range tasks {
if t.Done == done {
dst = append(dst, t)
}
}
return dst
}
If you just thought, “this looks like a ritual from ancient Gophers,” that is normal. You will get used to it: in Go, such things are considered readable because they are short and predictable.
Query validation and turning errors into ValidationError
Inside the handler, we do not want to spread out “if it failed here, write 400 like this, and if it failed there, do it differently”. We already agreed that we have a single error path through writeError, so the handler should return domain-meaningful errors: ValidationError for 400 and ErrNotFound for 404 (which is less common in list operations).
In this lecture, we will assume that the types ValidationError and writeError/mapError already exist (you wrote them in the lecture about a unified error contract). Then query validation turns into a simple rule: anything invalid is &ValidationError{Fields: ...}.
For example, if done is broken:
func invalidDoneQuery() error {
return &ValidationError{
Fields: map[string]string{
"done": "must be true or false",
},
}
}
And if sort is unknown:
func invalidSortQuery() error {
return &ValidationError{
Fields: map[string]string{
"sort": "supported: id, title",
},
}
}
This is convenient for the client: it always receives one format and can highlight the error next to a specific parameter. It is also convenient for you because the handler stays linear and readable.
3. Sorting and output stability
Sorting in a list endpoint is needed not only “for beauty”. It is needed for determinism: it is easier for the client (and your tests) to live when the same request always returns elements in the same order.
Key nuance: if you sort by a field that can be duplicated (for example, title), and do not define a secondary rule (tie-break), then the order of elements with the same title may “wander”. Even with the same code, the order of equal elements can change between environments and tool versions.
We introduce these rules:
- sort is absent or sort=id → sort by ID ascending
- sort=title → sort by Title, and if Title values are equal, sort by ID
Code:
import (
"fmt"
"sort"
)
func sortTasks(tasks []TaskDTO, sortBy string) error {
switch sortBy {
case "", "id":
sort.Slice(tasks, func(i, j int) bool { return tasks[i].ID < tasks[j].ID })
return nil
case "title":
sort.Slice(tasks, func(i, j int) bool {
if tasks[i].Title == tasks[j].Title {
return tasks[i].ID < tasks[j].ID
}
return tasks[i].Title < tasks[j].Title
})
return nil
default:
return fmt.Errorf("unsupported sort: %s", sortBy)
}
}
The ID tie-break makes the result deterministic even when names match. This is especially important if you later add tests that compare JSON “as a string”, or golden files.
4. Handler: pipeline parse → list → filter → sort → encode
A list handler is great because it perfectly trains the “server sequence muscle”. We want the code to be read top-down without jumping around the file.
Handler diagram:
flowchart TD
A[GET /api/v1/tasks] --> B[parse query: done/sort]
B --> C["app.List -> []TaskDTO"]
C --> D[optional filter done]
D --> E[sort + tie-break]
E --> F["encode JSON {tasks:...}"]
Now for the handler skeleton. Let's keep the service layer minimal for now:
import "context"
type TaskLister interface {
List(ctx context.Context) ([]TaskDTO, error)
}
And the handler itself:
import "net/http"
func (s *Server) handleListTasks(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
done, hasDone, err := parseOptionalBool(q, "done")
if err != nil {
writeError(w, &ValidationError{Fields: map[string]string{"done": "must be true or false"}})
return
}
sortBy, _, err := getSingleQuery(q, "sort")
if err != nil {
writeError(w, &ValidationError{Fields: map[string]string{"sort": "must be single"}})
return
}
tasks, err := s.app.List(r.Context())
if err != nil {
writeError(w, err)
return
}
if hasDone {
tasks = filterByDone(tasks, done)
}
if err := sortTasks(tasks, sortBy); err != nil {
writeError(w, &ValidationError{Fields: map[string]string{"sort": "supported: id, title"}})
return
}
writeJSON(w, http.StatusOK, ListTasksResponse{Tasks: tasks})
}
Notice a few “small things that are not small at all”:
- We always sort, even if sort is empty: this is stability by default.
- We filter after receiving the data: this keeps parse/query logic out of the app layer. This is not the only possible design, but it is good for teaching: the HTTP layer is responsible for the input/output contract.
- Query errors become ValidationError, and everything else is returned as the app layer decides, after which writeError will handle 400/404/500.
If you already have the writeJSON helper, it usually looks like this:
import (
"encoding/json"
"net/http"
)
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
Request examples
Server code is only half the story. The other half is how people actually use it. When you look at an API through the client’s eyes, it becomes immediately clear where the contract is leaky and where it is predictable.
Example 1: get all tasks, default sorting (by id)
curl -i "http://localhost:8080/api/v1/tasks"
Expected (example):
{
"tasks": [
{ "id": 1, "title": "Buy milk", "done": false },
{ "id": 2, "title": "Write Go code", "done": true }
]
}
Example 2: only completed tasks, sorted by title
curl -i "http://localhost:8080/api/v1/tasks?done=true&sort=title"
Example 3: query error
curl -i "http://localhost:8080/api/v1/tasks?done=tru"
And this is where it is especially important that the client receives not random text, but your unified error envelope, for example:
{
"error": {
"code": "validation",
"message": "invalid request",
"fields": {
"done": "must be true or false"
}
}
}
Even if the client is written in another language, this format is trivial to process: code defines the class, fields lets you highlight the specific location, and message shows it to a human.
5. Typical mistakes
Mistake #1: assuming that “if we do not sort, it will still be in order”.
As long as storage is a slice and tasks are only appended to the end, it may seem that the order is “stable by itself”. But once a map, file reading, merging from multiple sources, or simply an implementation change appears, the order becomes unpredictable. A good habit: the list endpoint is responsible for the order and always sorts before returning.
Mistake #2: forgetting that done has three states, and accidentally filtering by default.
If you do done, _ := strconv.ParseBool(q.Get("done")), then the absence of the parameter turns into false, and you suddenly return only unfinished tasks. The client will think that “the server is losing data”. There is only one fix: return (value, present, err) and apply the filter only when present.
Mistake #3: sorting by title without a tie-break and being surprised by a “jumping” order.
When two titles are equal, sorting without a secondary criterion does not promise that the elements will remain “as before”. Between tool versions or with a different data set, the order of equal elements may change. To avoid phantom test failures, add a tie-break (for example, id).
Mistake #4: accepting ?sort=id&sort=title and silently “taking the first value”.
Such an API becomes annoying to debug: the client made a mistake, and the server silently did “something”. In stable contracts, it is better either to document the rule “take the first value” clearly or, which is simpler for teaching and more reliable, to return 400, requiring a single parameter.
Mistake #5: returning a bare array instead of an object and then “having nowhere to expand”.
Today it may seem that the task list is just []TaskDTO. Tomorrow you may need total, the day after tomorrow — a timestamp or a version. If the response is already an object {"tasks": [...]}, you can add a field without pain. If the response is an array, you will have to break clients’ parsers. This is one of those rare cases where a small amount of JSON “redundancy” really saves weeks of life.
GO TO FULL VERSION