CodeGym /コース /Go SELF /Query params — filters, sorting, pagination

Query params — filters, sorting, pagination

Go SELF
レベル 57, レッスン 1
使用可能

1. Query params as part of the contract

最初に /api/v1/tasks?done=true&limit=20 を見たとき、こう思いたくなります。「まあ、? の後ろにあるただの文字列でしょ。何が違うの?」。しかし違いは非常に大きいです。query params は、リソースそのものを変えずに 出力を調整する 方法です。つまり、リソース自体は「task list」のままですが、サーバーに対して どの一覧が必要か、そして どう表示するか を伝えているのです。

task list リソース /api/v1/tasks には、ほぼ必ず 3 つの自然な「クライアントの要求」が生まれます。

1 つ目はフィルタリングです。完了済みだけ、未完了だけを表示したり、部分一致で検索したり、特定の tag を持つ task を選んだりします。2 つ目は sorting です。id や title で並べ替えます(そして、今日と明日で順序が変わっても驚かないようにします)。3 つ目は volume 制御です。2000 件ではなく 20 件だけ返す、つまり pagination です。

正しい philosophy を固定することが重要です。query params は一覧の見え方を制御する のであって、resource の識別の代わりにはなりません。もし「どの task か」を必ず指定したいなら、それは通常 path(/api/v1/tasks/{id})です。query は「出力設定」です。

2. Parameter dictionary for /api/v1/tasks

パラメータを 1 つずつ足していくと、すぐに混乱が起きます。今日は done、明日は isDone、明後日は completed となり、クライアントは苦痛と copy-paste の世界で生きることになります。そこで大人のやり方をします。task list 用の contract dictionary として、パラメータのセットを固定するのです。短く、安定していて、1 本の文字列に「全部の SQL を押し込む」ようなことはしません。

以下は基本 contract です(学習用プロジェクトとして十分で、ほとんどの単純な実 API にも通用します)。あえて最小限にしています。パラメータが少ないほど、保守しやすく、驚きも少なくなります。

Parameter Type (after parsing) Meaning Default value (if parameter is absent) Example
done
bool
(but the parameter is optional)
Filter by completion status no filter applied
done=true
q
string
Search by text (for example, in title) empty search (do not filter)
q=milk
tag
[]string
(repeating key)
Filter by tags no tag filtering
tag=go&tag=http
sort
enum (
id
,
title
)
Which field to sort by
id
sort=title
order
enum (
asc
,
desc
)
Sort direction
asc
order=desc
limit
int
How many items to return
20
limit=50
offset
int
Which item to start from
0
offset=100

There are two important semantic notes.

First, done is an optional filter. If done is not set, that does not mean done=false; it means “show everything”. We will come back to this idea, because it is a classic source of bugs.

Second, tag is a repeating parameter, and that is a normal, HTTP-style way to pass a list. Not a homemade CSV in one string, but exactly tag=go&tag=http.

3. Nuances of parameter design

Parameter naming

In API names, the compiler usually does not break — people do. A parameter is named once, a client bakes it into a mobile app, and suddenly it turns out that renaming it “without pain” is impossible. That is why query params should be treated like a public interface: boring, careful, predictable.

A simple rule works here: the parameter name should be short, clear, and free of creativity. We use lowercase and simple words: done, q, tag, sort, order, limit, offset. This is not self-expression; it is a contract.

A separate note about q. Beginners sometimes think: “Why not query?” You can use query too, but the short q is a familiar pattern (search forms, many APIs). The main thing is to choose one variant and stick to it.

About multi-word names. If you still need them, it is better to follow snake_case (for example, created_at, due_before), but in our current version of the contract we deliberately keep only single-word parameters to avoid unnecessary complexity.

Filters

Filters are where the user says: “I do not need the whole task list, I need a subset.” And here it is easy to accidentally make an API that seems to work, but cannot be explained or tested. That is why filters should be simple and composable.

The simplest and clearest composition model is: all filters are applied at once, i.e. logical AND.

For example, the request:

/api/v1/tasks?done=false&q=milk&tag=home&tag=shopping

should reasonably be read as: “Give me incomplete tasks whose text contains milk, and which have the tags home and shopping.” You can debate whether tags should mean AND or OR — and that is exactly the part of the contract that must be fixed in words.

For a learning project, it is convenient to adopt this rule: if several tag values are provided, the task matches if it contains at least one of the tags (OR inside tags), while the relation to other filters remains AND. So we get: “done filter AND search AND (tag1 OR tag2 OR ...)”. This is easier to explain to the user and easier to implement.

In this lecture we are not writing filtering code, but we are already designing the behavior so that it is predictable.

Sorting

Sorting seems simple until you realize that “by default” is also sorting — just implicit. And implicit sorting usually means “whatever happens”: today the database returned one order, tomorrow another, and the client’s tests start a “flaky dance”.

That is why a task list must have a deterministic default order. In our contract, that is sort=id and order=asc. Why id? Because it is the most stable and unambiguous field in a basic CRUD.

It is also useful to mentally agree on a tie-breaker (a secondary sort key). Even if we sort by title, two tasks may have the same name. Then the order still has to be stable — usually the secondary key becomes id. This is an implementation detail, but it is useful to keep in mind: otherwise sorting by title will “jump”, and the user will think the API has a life of its own.

The sort and order parameters are designed as a pair: sort answers “by what”, while order answers “in which direction”. This is simpler than trying to cram everything into one parameter like sort=title_desc.

Pagination

Pagination is not only a UI convenience, but also protection for the server (and the client) from accidentally “give me all tasks for all time”. If someone has ever done SELECT * without LIMIT on a million-row table, they later start respecting pagination almost religiously (and that is normal).

We use the simple limit/offset model. It is read like this: offset is how many items to skip from the beginning of the sorted list, and limit is how many to return after that.

For example: /api/v1/tasks?sort=id&order=asc&limit=20&offset=40

means: “Return tasks from 41st to 60th in ascending id order.” And here is an important thought: pagination only makes sense together with a fixed sort order. Otherwise the “pages” can get mixed up.

The contract should define reasonable limits. For example, the default limit is 20, and the maximum limit is 100. This is not a “teacher’s whim” — it is standard practice: if a client suddenly needs to export 5000 tasks, that is a separate scenario and should be handled deliberately (and often differently).

Repeating parameters

Repeating query params can look strange to people who are used to passing arrays in JSON. But in a URL, this is a natural pattern: one key can have several values, because a query string is conceptually closer to map[string][]string than to map[string]string.

So tag=go&tag=http is not a “hack” or a “workaround”, but a standard way to express a list. You will see it in many different systems, from simple REST APIs to complex search queries.

From a practical point of view, this gives a nice property: if a client wants to add a tag, it does not need to parse a CSV string, carefully escape commas, and think about what to do with a tag like dev,ops. It just adds another tag.

In Go’s standard library, this is modeled exactly that way: when parsing a query, you get a structure where a key can have multiple values, and then code can take either the first value or all of them at once. Even in examples where a single value is taken from a query via r.URL.Query().Get("guess"), the assumption is that a query is a set of parameters the server reads structurally, not by “splitting on ampersands”.

4. Request examples for /api/v1/tasks

Once the contract is fixed, it becomes easier to “think in URLs”. That is a useful skill: you look at a link and understand what the server should do, without guesswork or magic.

Here are a few examples (and how to interpret them correctly).

package main

import "fmt"

func main() {
	fmt.Println("/api/v1/tasks") // task list without filters, sort=id, order=asc, limit=20, offset=0
}

There is no query at all here. And that is fine: defaults are part of the contract, and the absence of parameters should have a clear meaning.

package main

import "fmt"

func main() {
	fmt.Println("/api/v1/tasks?done=true") // only completed, other parameters use defaults
}

done=true applies the filter, but does not change sorting or pagination.

package main

import "fmt"

func main() {
	fmt.Println("/api/v1/tasks?q=milk&tag=home&tag=shopping") // search + tags
}

We read this as: “search for milk and filter by tags”. How exactly multiple tags are interpreted (OR or AND) is fixed in the contract beforehand, not “whatever happens”.

package main

import "fmt"

func main() {
	fmt.Println("/api/v1/tasks?sort=title&order=desc&limit=10&offset=20") // sorting + pagination
}

Here the request already looks like a “full” client listing: we sorted by title in descending order and took a page.

5. Parameter model in code

At this point it is tempting to immediately rush into parsing limit with strconv.Atoi and validating sort with a whitelist. But according to our plan for the day, that will be in the next steps. Here we do exactly one useful thing: we design a type in code that stores typed listing parameters.

This helps avoid mixing “parameter reading” and “task list business logic”. We want to move toward this scheme: first parse and validate input, obtain a parameter structure, and only then pass it to the function that knows how to select tasks.

package main

type TaskListQuery struct {
	// Done: nil = filter not set, true/false = filter set.
	Done *bool

	Q    string   // search string
	Tags []string // repeating tag=...

	Sort  string // "id" or "title"
	Order string // "asc" or "desc"

	Limit  int
	Offset int
}

Pay attention to *bool. This is not “Go's love of pointers”; it is a way to honestly store three states: “not set”, “true”, “false”. If you use plain bool, you cannot distinguish done=false from “done was not sent”. And that changes the meaning.

Now let’s define defaults. It is more convenient to manage defaults centrally rather than scattering 20 and id throughout the code like confetti.

package main

func DefaultTaskListQuery() TaskListQuery {
	return TaskListQuery{
		Done:   nil,
		Q:      "",
		Tags:   nil,
		Sort:   "id",
		Order:  "asc",
		Limit:  20,
		Offset: 0,
	}
}

And now we have a clear boundary: the query params parser should take DefaultTaskListQuery(), apply what came from the client, and either return a ready structure or a validation error. We will implement the parsing itself later (and that is where url.Values, Get, lists of values, and so on will appear).

By the way, in Go the standard library shows that “parse query → get string → convert → validate” is absolutely normal: first you take a string value from the query, then turn it into a number and check boundaries. And if you need to parse a query as a separate string (without a full URL), there is a standard tool for that too: query-string parsing followed by Encode() even appears in test examples.

6. Common mistakes when designing query params

Mistake #1: making required parameters in the query.
If the client must pass id as ?id=123, you are almost certainly making life harder: that is resource identification, not output configuration. Identification lives in the path, while query is for filters/sorting/pagination.

Mistake #2: not fixing defaults and “hoping for common sense”.
Without defaults, the contract turns into guessing: the client does not know how many items will be returned, in what order, or what “no parameter” means. A default is not a minor detail; it is part of the public behavior of the API.

Mistake #3: confusing “parameter is absent” with “parameter is false/0/empty”.
Classic example: done=false versus absent done. If you store done as a bool, you will inevitably end up with logic like “how do I tell whether it was passed?”. In the end, the code starts inventing heuristics and bugs appear “out of nowhere”.

Mistake #4: accepting any sort values and “sorting it out later”.
If the server silently accepts sort=banana, and then either crashes or sorts in some “default” way, the client does not understand what went wrong. Enumerations need a whitelist of allowed values — otherwise the contract becomes fuzzy.

Mistake #5: not limiting limit and not thinking about load.
limit=1000000 is not “the user wanted it”; it is a potential attack or at least an accidental overload. Even in a learning project, it is useful to think like an engineer: set reasonable boundaries and explain them with a validation error.

1
タスク
Go SELF, レベル 57, レッスン 1
ロック未解除
タスクリンクジェネレーター
タスクリンクジェネレーター
1
タスク
Go SELF, レベル 57, レッスン 1
ロック未解除
タスクのフィルタの読み取り
タスクのフィルタの読み取り
1
タスク
Go SELF, レベル 57, レッスン 1
ロック未解除
フィルタの正規化
フィルタの正規化
1
タスク
Go SELF, レベル 57, レッスン 1
ロック未解除
出力シミュレータ
出力シミュレータ
コメント
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION