CodeGym /Cursos /Go SELF /POST create — decode JSON, validate, responses 201/400

POST create — decode JSON, validate, responses 201/400

Go SELF
Nível 61, Lição 0
Disponível

1. The contract POST /api/v1/tasks

Before writing code, it is useful to pause for a minute and agree on the rules of the game. HTTP API is not “whatever happens”, but a contract between client and server. If the contract is unstable, the client starts guessing behavior from error text, and that is roughly like fixing a printer with a shamanic drum: it sometimes works, but it is embarrassing.

In this lecture we are building task creation and fixing the contract:

  • Method and path: POST /api/v1/tasks
  • Request body: JSON object of the form { "title": "..." }
  • On success: 201 Created, Location header: /api/v1/tasks/{id}, response body — the created task as JSON
  • On bad input: 400 Bad Request in a unified error envelope, error code validation, and in fields we put an explanation of what exactly is wrong

There is an important psychological detail here: 400 is not “the server is being nasty”, it is “the client asked for something strange”. That is why we must respond predictably and consistently across all endpoints.

A small sketch of the handler pipeline — we will stick to it throughout the module so the code does not turn into spaghetti:

flowchart LR
  A[HTTP request] --> B[Decode JSON]
  B --> C[Validate + normalize]
  C --> D[App/Create]
  D --> E[201 + Location + JSON body]
  B -->|bad json| X[400 validation]
  C -->|invalid fields| X
  D -->|unexpected| Y[500 internal]

2. DTO and input validation

When a beginner sees JSON, there is often a temptation: “What if I just make a type Task struct and directly json.Unmarshal into it?” It looks short, but it usually breaks at the first turn.

The problem is that the request JSON structure (the external contract) and the domain model structure (the internal invariants) are different entities. A request can be incomplete, misspelled, have extra fields, have spaces, and the domain model must be neat and “internally correct”.

That is why we make two DTOs:

  • CreateTaskRequest — what comes from the client
  • TaskDTO (or TaskResponse) — what we return outward

Request DTO

Minimal request DTO example:


package api

type CreateTaskRequest struct {
	Title string `json:"title"`
}

That is only one useful field, but it is already important: we explicitly say “in JSON we expect the title field”. Next we will add validation, because JSON itself does not guarantee anything except that it “looks like JSON”.

Normalization and checking title

Validation is the boring part of programming, like washing dishes: nobody likes it, but without it things eventually start to stink. In APIs, validation is especially important, because “dirty input” is not an exception, but a statistically inevitable reality.

We need at least two actions:

1) Normalize the string (remove leading and trailing spaces), so " buy milk " becomes "buy milk".

2) Check that after normalization the string is not empty. An empty title means the task cannot be shown to the user properly.

Let us add a Validate() method to the DTO. It will return our typed ValidationError, so the shared writeError (already introduced in the previous lecture) returns 400 in the correct format.

package api

import "strings"

func (r CreateTaskRequest) Validate() error {
	if strings.TrimSpace(r.Title) == "" {
		return &ValidationError{
			Fields: map[string]string{"title": "must not be empty"},
		}
	}
	return nil
}

Notice the detail: we return *ValidationError, not just fmt.Errorf("bad title"). That way the error will be recognized reliably, even if it gets wrapped somewhere above (fmt.Errorf("create task: %w", err)), because in Go the convention is to “carry context up the stack” and classify the error separately.

Response DTO and mapping

The response DTO can be very simple:

package api

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

Mapping from the domain app.Task to TaskDTO is usually done explicitly. Yes, that is 3 assignments. But then you do not cry later when the domain model changes and you want to keep the API compatible.

package api

import "example.com/project/app"

func toTaskDTO(t app.Task) TaskDTO {
	return TaskDTO{ID: t.ID, Title: t.Title, Done: t.Done}
}

3. Decoding JSON: strict and safe

Now let us move on to the “Decode JSON” part. There are several typical threats here (do not be scared by the word “threats” — this is not cyberpunk, just practice).

The first threat: the client may send a very large body, and you may accidentally read it all, wasting memory and time. Even without malicious intent, this happens when the client has a bug.

The second threat: the client sent JSON with extra fields, for example { "titlle": "..." } (a typo). If we are not strict, the server will “silently ignore” the field and create a task with an empty title, and then we will wonder why empty tasks appear in the database.

The third threat: the client sent two JSON objects in a row: {...}{...}. Formally this is a stream of JSON values, but for an HTTP API this is almost always an error. We agreed: the body contains exactly one JSON object.

We write a decodeJSON helper that does three things: limits the size, enables strict mode, and checks for “one object”.

package api

import (
	"encoding/json"
	"io"
	"net/http"
)

func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) error {
	r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // 1 MiB
	defer r.Body.Close()

	dec := json.NewDecoder(r.Body)
	dec.DisallowUnknownFields()

	if err := dec.Decode(dst); err != nil {
		return &ValidationError{Fields: map[string]string{"body": "invalid json"}}
	}
	if err := dec.Decode(&struct{}{}); err != io.EOF {
		return &ValidationError{Fields: map[string]string{"body": "must contain single json object"}}
	}
	return nil
}

Yes, the messages "invalid json" and "must contain single json object" look simple. And that is good: outwardly we return stable and safe wording, and details (if we want) we can log separately at the boundary. This is discipline: the API does not turn into a “leak of internal messages” outward.

4. Application layer: creating a task outside the handler

It is very tempting to put everything directly into handleCreateTask: parse JSON, validate, add to a slice, return a response. But then the task-creation logic lives inside the HTTP layer, and we cut off our path to a proper architecture: any reuse or testing becomes painful.

So we keep a simple model: the handler calls app.Create(...). Here app is the application layer that knows the domain rules.

Minimal domain task structure for the educational project:

package app

type Task struct {
	ID    int
	Title string
	Done  bool
}

And the simplest in-memory service that creates tasks. We are not discussing concurrency and locks here — that is a separate topic, and right now we need to understand the data flow.

package app

import "context"

type App struct {
	nextID int
	tasks  []Task
}

func (a *App) Create(ctx context.Context, title string) (Task, error) {
	a.nextID++
	t := Task{ID: a.nextID, Title: title, Done: false}
	a.tasks = append(a.tasks, t)
	return t, nil
}

ctx is not used yet, but this is normal practice: the HTTP layer always passes r.Context() down so request cancellation can “reach” deeper in the stack when we start doing I/O or long-running operations.

5. Response 201 Created: Location and headers

Now the nicest part: the successful response. But HTTP, like a proper protocol, has its own “rules of good manners”.

When you create a resource, status 201 Created tells the client: “I created a new entity”. The Location header says: “here is the address of that entity”. Even if the client will not do a GET to that address right now, the contract becomes richer and more convenient.

And there is a purely technical Go nuance here: headers must be set before WriteHeader. After WriteHeader, the headers have already gone out on the network, and it is too late to wave your fists.

6. Handler handleCreateTask: the full path

Now let us assemble the full handler. It will look linear and boring — and that is a compliment. A good handler should read from top to bottom like an instruction manual: “first decode, then validate, then create, then respond”.

Assume we already have writeError(w, err) from the previous lecture (a single error-response entry point), as well as Server with a dependency on app.

package api

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strings"

	"example.com/project/app"
)

type Server struct {
	app *app.App
}

func (s *Server) handleCreateTask(w http.ResponseWriter, r *http.Request) {
	var req CreateTaskRequest
	if err := decodeJSON(w, r, &req); err != nil {
		writeError(w, err)
		return
	}
	if err := req.Validate(); err != nil {
		writeError(w, err)
		return
	}

	title := strings.TrimSpace(req.Title)
	t, err := s.app.Create(r.Context(), title)
	if err != nil {
		writeError(w, err)
		return
	}

	w.Header().Set("Location", fmt.Sprintf("/api/v1/tasks/%d", t.ID))
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(http.StatusCreated)
	_ = json.NewEncoder(w).Encode(toTaskDTO(t))
}

Several important observations about this code.

First, there is no place here where we “guess” the status manually for errors. We simply return the error upward to writeError, and it already knows that ValidationError means 400.

Second, we normalize title once in one place (title := strings.TrimSpace(req.Title)), so the domain receives a clean value. This is a good style: the boundary is responsible for cleaning input.

Third, we set Location before WriteHeader, and Content-Type also before. Otherwise you may get “it seems to work, but somehow the header is missing”.

Why “broken JSON” is 400, not 500

A very common beginner mistake: if json.Decoder.Decode returned an error, then “something broke”, therefore 500. But that is a logical trap.

500 means: “the client did everything right, and the server itself fell over for no reason”. Broken JSON is almost always the client’s fault. Therefore it is 400 (validation), even if the text inside the error was scary.

In Go this fits nicely into the idea of “errors as values”: you do not have to treat every error as a catastrophe, you have to classify it and make a decision.

Route registration

Finally, a small glue piece: how to mount this handler on ServeMux. We assume Go 1.22+ patterns, so the route string includes the method.

package main

import (
	"net/http"

	"example.com/project/api"
	"example.com/project/app"
)

func main() {
	a := &app.App{}
	srv := &api.Server{app: a}

	mux := http.NewServeMux()
	mux.HandleFunc("POST /api/v1/tasks", srv.handleCreateTask)

	_ = http.ListenAndServe(":8080", mux)
}

If your field in Server is named differently, adjust the initialization. What matters now is the route idea itself: POST should reach the right handler, and the handler should go through the same clear pipeline.

7. Typical mistakes when implementing POST /api/v1/tasks

Mistake #1: json.Unmarshal instead of json.Decoder and “I read the whole body at once”.
People often write body, _ := io.ReadAll(r.Body) and then json.Unmarshal(body, &dst). This works for small requests, but it gives you extra allocations and the risk of accidentally reading a huge body. With json.Decoder and MaxBytesReader you set a limit right away and decode as a stream.

Mistake #2: did not enable DisallowUnknownFields(), so typos pass silently.
The client sent { "titlle": "buy milk" }, the server said nothing, created a task with an empty title, and then you chase the bug “tasks are empty”. A strict decoder turns such situations into a clear 400 validation error.

Mistake #3: did not check for “exactly one JSON object” and accepted garbage after JSON.
Some clients may accidentally (or intentionally) send {...}\n{...}. If you do one Decode, you read only the first object and “leave a tail”. A second Decode with an io.EOF check makes the contract honest: the body must contain one value.

Mistake #4: you do validation inside app.Create, but do not return ValidationError from the handler.
If validation returns just errors.New("bad title"), the shared error mapping may decide this is internal, and you get 500 instead of 400. For bad input, stick to a typed ValidationError so it can be recognized through errors.As even with wrapping.

Mistake #5: set Location after WriteHeader.
In Go, headers are sent together with the status. If you first do w.WriteHeader(http.StatusCreated), and only then w.Header().Set("Location", "..."), then Location will already not reach the client. This is one of those bugs that is especially annoying because the code “looks right”, but does not work.

1
Tarefa
Go SELF, nível 61, lição 0
Bloqueado
Título da tarefa
Título da tarefa
1
Tarefa
Go SELF, nível 61, lição 0
Bloqueado
JSON estrito
JSON estrito
1
Tarefa
Go SELF, nível 61, lição 0
Bloqueado
Criação de tarefa
Criação de tarefa
1
Tarefa
Go SELF, nível 61, lição 0
Bloqueado
Erros unificados
Erros unificados
Comentários
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION