1. Query params as part of the contract
처음 /api/v1/tasks?done=true&limit=20를 보면, 「그냥 ? 뒤에 붙은 문자열일 뿐인데, 뭐가 다르지?」라고 생각하고 싶어집니다. 하지만 차이는 매우 큽니다. query params는 리소스 자체를 바꾸지 않고 응답을 조정하는 방법입니다. 즉, 리소스는 여전히 「task list」로 남아 있지만, 서버에게 어떤 목록이 필요한지와 어떻게 보여줄지를 알려줍니다.
작업 목록 리소스 /api/v1/tasks에는 거의 항상 세 가지 자연스러운 「client needs」가 생깁니다.
첫 번째는 목록을 필터링하는 것: 완료된 항목만 또는 미완료 항목만 보여주기, 부분 문자열로 검색하기, 특정 태그가 있는 작업 선택하기. 두 번째는 정렬: id 기준, 이름 기준(그리고 오늘은 하나였다가 내일은 다른 결과가 나온다고 놀라지 않기). 세 번째는 양 제한: 2000개가 아니라 20개의 작업을 가져오기, 즉 pagination입니다.
올바른 철학을 고정하는 것이 중요합니다. query params는 목록의 표현을 제어하지만 리소스 식별을 대체하지는 않습니다. 반드시 「어떤 구체적인 task인지」를 지정해야 한다면, 보통은 path(/api/v1/tasks/{id})를 사용하고 query는 아닙니다. Query는 「응답 설정」입니다.
2. Parameter dictionary for /api/v1/tasks
파라미터를 하나씩 추가하기 시작하면 금방 혼란이 생깁니다. 오늘은 done, 내일은 isDone, 그다음 날은 completed가 되고, client는 고통과 복붙의 세계에서 살게 됩니다. 그래서 우리는 성숙한 방식을 택합니다. 작업 목록에 대한 contract dictionary를 고정하는 것입니다. 이 사전은 짧고, 안정적이어야 하며, 「SQL 전체를 한 줄에 욱여넣기」를 시도해서는 안 됩니다.
아래는 기본 계약입니다. 학습 프로젝트와 거의 모든 단순한 실제 API에 충분합니다. 우리는 의도적으로 최소한만 유지합니다. 파라미터가 적을수록 유지보수는 쉬워지고 surprises도 줄어듭니다.
| Parameter | Type (after parsing) | Meaning | Default value (if absent) | Example |
|---|---|---|---|---|
|
(but optional) |
Completion-status filter | no filter applied | |
|
|
Text search (for example, in title) | empty search (do not filter) | |
|
(repeating key) |
Tag filter | no tag filtering | |
|
enum (, ) |
Which field to sort by | |
|
|
enum (, ) |
Sort direction | |
|
|
|
How many items to return | |
|
|
|
Which item to start from | |
|
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 return to this idea, because it is a classic source of bugs.
Second, tag is a repeating parameter, and that is a normal, HTTP-like way to pass a list. Not a homemade CSV in one string, but exactly tag=go&tag=http.
3. Nuances of parameter design
Naming parameters
In API naming, the compiler usually does not break — people do. A parameter is named once, the 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, neat, predictable.
A simple rule works here: the parameter name should be short, clear, and free of fancy ideas. 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. Sometimes beginners 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 they are really needed, it is better to use snake_case (for example, created_at, due_before), but in our current contract version we intentionally keep only single-word parameters to avoid unnecessary complexity.
Filters
Filters are the place where the user says: 「I do not need the whole task list, I need a subset.」 And here it is easy to accidentally create an API that seems to “work” but cannot be explained or tested. Therefore filters should be simple and composable.
The simplest and clearest composition model is that all filters are applied simultaneously, that is, logical AND.
For example, the request:
/api/v1/tasks?done=false&q=milk&tag=home&tag=shopping
can be read as: 「Give me incomplete tasks whose text contains milk, and which have the tags home and shopping.」 One can debate whether tags should mean AND or OR — and that is exactly 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 relative to the other filters it is still AND. This becomes: 「done-filter AND search AND (tag1 OR tag2 OR ...)」. It is easier to explain to the user and simpler to implement.
For this lecture we are not writing the filtering code, but we are already designing 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 tests start doing the “flaky dance”.
Therefore the task list must have a defined deterministic default order. In our contract this is sort=id and order=asc. Why id? Because it is the most stable and unambiguous field in basic CRUD.
It is also useful to mentally agree on a tie-breaker (secondary sort key). Even if we sort by title, two tasks can have the same title. Then the order must still be stable — usually the second 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 the question “by what”, and 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 about interface convenience, but also about protecting the server (and the client) from accidentally saying “give me all tasks for all time”. If someone has ever done SELECT * without LIMIT on a table with a million rows, they later begin to respect pagination almost religiously (and that is normal).
We use a simple limit/offset model. It reads like this: offset is how many items to skip from the start 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 41 through 60 in ascending id order.」 And here is an important thought right away: pagination only makes sense together with fixed sorting. Otherwise “pages” can get mixed up.
Reasonable limits should be fixed in the contract. 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 the client suddenly needs to export 5000 tasks, that is a separate scenario and should be handled intentionally (and often differently).
Repeated parameters
Repeated query params sometimes 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 multiple values, because 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 “crutch”, but a standard way to express a list. You will see it in many systems, from simple REST APIs to complex search queries.
From a practical standpoint, this gives a pleasant property: if the client wants to add a tag, they do not need to parse a CSV string, carefully escape commas, and wonder what to do with a tag like dev,ops. They simply add another tag.
In the Go standard library, this is modeled exactly that way: when parsing query, you get a structure where a key can have several values, and then the code can take either the first value or all of them at once. Even in examples where a single value is taken from query via r.URL.Query().Get("guess"), the assumption is that query is a set of parameters that 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”. This is a useful skill: you look at a link and understand what the server should do, without guessing 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 normal: defaults are part of the contract, and the absence of parameters must 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」. Exactly how several tags are interpreted (OR or AND) is fixed in the contract in advance, not “however it turned out”.
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: sorted by title in descending order and a page is taken.
5. Parameter model in code
Right now it is tempting to immediately start parsing limit with strconv.Atoi and validating sort with a whitelist. But according to our plan for the day, that will be the next step. Here we do exactly one useful thing: we design the type in code that stores typed listing parameters.
This helps avoid mixing “parameter reading” with “task list business logic”. We want to reach a scheme where we first parse and validate the input, get 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 will not be able to distinguish done=false from “done was not sent”. And that is a different meaning.
Now let us set defaults. It is more convenient to manage defaults centrally than to scatter 20 and id through 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-made 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 completely normal: first you take a string value from query, then turn it into a number and check the bounds. And if you need to parse a query as a separate string (without a full URL), there is also a standard tool for that: parsing a query string followed by Encode() appears even in testing examples.
6. Typical mistakes when designing query params
Mistake #1: making required parameters in query.
If the client must pass id as ?id=123, you are almost certainly making life harder: that is resource identification, not response configuration. Identification belongs 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, and 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 absent” with “parameter equals false/0/empty”.
Classic example: done=false versus missing done. If you store done as a bool, you will inevitably end up with logic like “how do I know whether it was passed”. As a result, the code starts inventing heuristics and bugs appear “suddenly”.
Mistake #4: accepting any sort values and “dealing with it 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 require a whitelist of allowed values — otherwise the contract becomes blurry.
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.
GO TO FULL VERSION