1. Why do we need a done endpoint at all
When you build CRUD for tasks, the moment of truth arrives: “Okay, we create and read tasks, but how do we change their state?” In educational projects, it is tempting to just write task.Done = true and move on. But in an HTTP API this becomes a separate contract: which method, which path, what do we return, is the action idempotent, and what should happen on repeated calls. And it is exactly at such “simple” places that you most often end up with an API that is awkward to maintain later.
Let us imagine that a task is a resource, and the resource has a done state (completed / not completed). The client (CLI, frontend, another service) should be able to tell the server: “mark this task as completed.” Technically, this is an update. But updates in HTTP come in different forms, and next we will look at how to choose the right one and avoid confusing either the client or yourself a week later.
PATCH vs POST: what do we choose and why
If you are just starting out, a perfectly natural thought is: “We have an action called ‘mark done’, so we should use POST: /tasks/{id}/done”. This is the logic of “POST = perform an action”. It is not entirely wrong, but it has side effects: you mix “resource” and “command”, and you also risk losing idempotency (and then wondering why client retries break your life).
For “change part of a resource” in HTTP, PATCH is usually the right fit. Mentally, it sounds like this: “I am not recreating the task as a whole (not PUT), I am not creating a subresource (not POST), I am partially changing an existing resource.” And marking it as done is exactly such a partial change.
At the same time, there are two popular designs:
- PATCH /api/v1/tasks/{id} with a body {"done": true}
- PATCH /api/v1/tasks/{id}/done without a body (or with one, but usually without)
For this lesson, we will use the more straightforward and beginner-friendly option: PATCH /api/v1/tasks/{id}/done, because it is easier to read and easier to validate (we do not need to parse JSON just to get true). And it also fits nicely with the idea of an “endpoint for changing state”.
To avoid turning this into a religious war of “PATCH vs POST”, let us pin down a useful table — it is not the ultimate truth, but it does a great job of organizing your thoughts:
| Option | Example | Pros | Cons |
|---|---|---|---|
|
|
closer to “changing part of a resource”, easier to make idempotent | sometimes people argue that “done” looks like a command |
|
|
reads well as an action | more often associated with “create / start”, easy to make non-idempotent by accident |
My practical advice: if an action is, in terms of meaning, a change to the resource state, and you want repeated calls not to create chaos, use PATCH.
2. Idempotency: why a repeated request should not make “even more done”
The word “idempotency” sounds like a spell from a math textbook (and yes, it is intimidating). But in HTTP it is a very down-to-earth idea: if the client repeats a request because of a network failure or timeout, the result should remain predictable.
For “mark done”, we want:
- the first call to make the task completed;
- the second / third / fiftieth call to not corrupt the data and not turn done into “done done done”.
So the operation is idempotent by meaning: after execution, the state is the same.
From this follows an important domain-layer contract: the MarkDone(id) method should behave calmly even if the task is already done=true. The possible behaviors differ, but for our educational API the following is convenient:
- if the task exists, we guarantee done=true and return success;
- if the task does not exist, return ErrNotFound (possibly wrapped);
- if id is invalid, that is a validation error before the domain layer.
4. 200 vs 204: what to return to the client
Now for the most interesting part: what do we return in response to a successful “mark done”.
There are two main options:
- 204 No Content — success without a response body
- 200 OK — success with a body, for example return the updated task
Both options are valid, but they lead to different client behavior.
Option A: 204 No Content
This option says: “I did it. I will not say anything else.” It is good because:
- simpler implementation (no DTO needed, no json.NewEncoder(w).Encode(...) needed);
- less traffic;
- fewer chances to accidentally drift away from the response format.
But there is a strict nuance: with 204 you must not write a body. That means at all. Not even "ok". Not even a single space. Not even “honestly, it is only 2 bytes”. Some proxies and clients will behave strangely.
Option B: 200 OK + JSON
This option says: “I did it, and here is the final state.” It is good because the client does not need an extra GET just to see the updated fields.
But here you pay with complexity: you need to decide what exactly to return. The full task? Only {"id":10,"done":true}? And you also need to keep the DTO stable.
For this lesson, we choose 204 No Content as the default, “clean”, and easy-to-maintain contract. If you really want to return JSON, that is also possible, but then make that agreement explicit and keep the style consistent across the entire API.
A small mini-diagram to reinforce the difference in “feel” between these options:
sequenceDiagram
participant C as Client
participant S as Server
C->>S: PATCH /tasks/10/done
alt 204 No Content
S-->>C: 204 (no body)
Note over C: If desired, the client does a GET
else 200 OK + body
S-->>C: 200 + {"id":10,"done":true,...}
Note over C: The client sees the result immediately
end
5. Endpoint contract: method, path, input, output
Now we will fix the contract so that it can be read as a “deal”, not as “well, it works roughly like this”.
We implement:
- Method: PATCH
- Path: /api/v1/tasks/{id}/done
- Path params: {id} — required, integer > 0
- Request body: absent
- Success: 204 No Content
- Errors:
- 400 (validation) if id is empty / not a number / <=0
- 404 (not_found) if the task does not exist
- 500 (internal) for other unexpected problems
Notice an important point of pedantry: “id is not a number” is not 404. It is bad input, which means 400. We reserve 404 for the situation where the number is valid, but the resource does not exist.
6. Routing in Go 1.22+: registering the handler
Before writing the handler, we need to give it an address in ServeMux. Since we are on Go 1.22+ and use patterns with a method, this reads very cleanly: the route string documents the contract by itself.
package main
import (
"net/http"
)
func routes(s *Server) *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("PATCH /api/v1/tasks/{id}/done", s.handleMarkDone)
return mux
}
Pay attention to an important detail: we are not “gluing strings together” and we are not trying to parse the URL manually. The path parameter {id} is then obtained via r.PathValue("id"). This removes a lot of routine work and reduces the chance of making a mistake while parsing the path.
7. Unified parsing of {id}: parseID and ValidationError
The purpose of parseID in our application is not only to turn a string into a number. The main thing is that all endpoint’s should interpret a bad id in the same way and return the same validation error shape.
Example (a reminder: this may have already been written earlier; here we are only fixing the idea of which error we want to return):
package main
import (
"strconv"
)
func parseID(raw string) (int, error) {
id, err := strconv.Atoi(raw)
if err != nil || id <= 0 {
return 0, &ValidationError{
Fields: map[string]string{"id": "must be positive integer"},
}
}
return id, nil
}
Important point: parseID returns exactly ValidationError, so that writeError can consistently turn it into 400 with fields. In other words, the handler does not decide “what an id error is” — it just calls a common helper.
8. Handler: parse → app → status
The done handler is a great example of “short and honest code”. It should look as linear as possible: parse the id, call the domain operation, return 204. No JSON encoders, no “let us also print a log into the response”.
package main
import (
"net/http"
)
func (s *Server) handleMarkDone(w http.ResponseWriter, r *http.Request) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(w, err)
return
}
if err := s.app.MarkDone(r.Context(), id); err != nil {
writeError(w, err)
return
}
w.WriteHeader(http.StatusNoContent) // 204
}
If you catch yourself thinking, “maybe we should write fmt.Fprintln(w, "ok")?”, stop. With 204 that would violate the contract. In the API world, “I just wrote a little body” is like “I just slightly broke the protocol”: it sounds minor, but later someone will be debugging this at night.
9. Domain layer: how to return not_found
The HTTP layer should not “understand the database” or storage details. It knows how to map domain error classes to HTTP codes. Therefore, the domain layer must return errors in a way that keeps classification stable.
We agreed that not found is the sentinel ErrNotFound, recognized through errors.Is. And this is very important: if you add context with fmt.Errorf, use %w, so the error remains recognizable in the chain. In Go, this is the standard practice for working with sentinel errors.
Here is a minimal example of a domain method:
package main
import (
"context"
"fmt"
)
func (a *App) MarkDone(ctx context.Context, id int) error {
ok := a.store.SetDone(id, true)
if !ok {
return fmt.Errorf("mark done %d: %w", id, ErrNotFound)
}
return nil
}
Why do we do this? Because errors.Is(err, ErrNotFound) will work even when wrapped (wrapping), and that is much more reliable than err == ErrNotFound.
10. If the task is already done: error or success?
This is the place where many beginners (and not only beginners) start arguing with reality. It seems logical: “If it is already done, then it is an error.” But in an API this often turns into inconvenience: the client has to do a GET first to find out the state, then decide whether to call PATCH or not. And what if two clients act at the same time? What if the UI is on a phone and the network is flaky?
For our educational contract, a practical rule is convenient: if the task exists, MarkDone is always a success, even if it is already done=true. This makes the operation naturally idempotent. The client can safely repeat the request, and the state does not break.
If you really want to tell the client “it was already completed”, you can do that only if you return 200 with a body and, for example, a field updated: false. But that complicates the contract, and for the basic course we do not take that path: 204 is simpler, cleaner, and gives fewer surfaces for bugs.
11. Alternatives: POST and a 200 response
If you still choose POST
Sometimes you will see APIs that use POST /tasks/{id}/done. This is especially common in systems built around “commands” (command-style API) or events (event-style). There POST means “create an event / perform an action”, and that is perfectly fine in its own architecture.
But if you choose POST, you need to be twice as careful about idempotency. If the client repeats the POST because of a retry, and your server naively writes a “done” event into a log, queue, or history, you may end up with two events instead of one. Sometimes that is acceptable, sometimes it breaks analytics, and sometimes it breaks billing (and then you get a new friend — the accountant).
That is why, in our project, PATCH remains the safer choice, because the semantics of “partial update” are originally closer to “set done=true”.
If you return 200 OK + JSON
So that you do not think 204 is the only religion, let me show what “200 OK + return the task” would look like. This is useful at least for understanding the price you pay for client convenience.
Suppose MarkDone returns an updated DTO:
package main
import (
"context"
)
type TaskDTO struct {
ID int `json:"id"`
Title string `json:"title"`
Done bool `json:"done"`
}
type TaskApp interface {
MarkDone(ctx context.Context, id int) (TaskDTO, error)
}
Then the handler will no longer be as minimal:
package main
import (
"encoding/json"
"net/http"
)
func (s *Server) handleMarkDone200(w http.ResponseWriter, r *http.Request) {
id, err := parseID(r.PathValue("id"))
if err != nil {
writeError(w, err)
return
}
task, err := s.app.MarkDone(r.Context(), id)
if err != nil {
writeError(w, err)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_ = json.NewEncoder(w).Encode(task) // 200 by default
}
Notice how more decisions appear immediately: which DTO, which fields, what to do with Title (what if we do not want to expose it?), how to maintain compatibility. That is why in the current module we prefer 204: it teaches careful minimalism and stable contracts.
12. Typical mistakes
Mistake #1: returning 404 when id is not a number.
This is one of the most common logical mistakes: “well, if it was not found, then it is 404.” But id=abc is not “resource not found”, it is “the client sent garbage”. So validation always comes first, and then 400 validation; 404 not_found is only for the case where id is valid, but the entity does not exist.
Mistake #2: writing a body with 204 No Content.
This often looks harmless: w.WriteHeader(204) and then fmt.Fprintln(w, "ok"). On local tests it “seems to work”, and then the client or a proxy starts acting weird. If the contract is 204, then after WriteHeader you just return from the handler and do not try to be “helpful with text”.
Mistake #3: using err == ErrNotFound and losing not found after wrapping.
When the domain layer adds context with fmt.Errorf("...: %w", ErrNotFound), the comparison err == ErrNotFound stops working. The correct path for a sentinel is errors.Is(err, ErrNotFound), because it walks the wrapper chain.
Mistake #4: implementing “done” as a non-idempotent action.
Sometimes inside people make a “toggle” (done = !done) or “if already done — return an error”. That turns a repeated request (which in reality happens because of retries) into a source of random bugs. For a basic API, the safer and simpler contract is “after the call, done=true”.
Mistake #5: creating different {id} parsing logic in different handlers.
One handler considers id=0 valid, another treats it as an error; one returns {"id":"bad"}, another — {"path":"bad"}. From the outside, it looks like you have two different APIs in one. The fix is simple: one parseID and one ValidationError, and then one writeError for everyone.
GO TO FULL VERSION