CodeGym /コース /Go SELF /JSON API: headers, DTOs, and a unified error envelope

JSON API: headers, DTOs, and a unified error envelope

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

1. Why fix a JSON contract

When people hear “JSON API,” they often think: “Well, it is simple: send JSON, receive JSON.” But “just JSON” is like “just agreeing to meet”: without time, address, and the phrase “in what format are you waiting for me,” the meeting turns into a series. A JSON API contract is not only “which fields,” but also “which headers,” “what to do on error,” and “how the client recognizes a problem without parsing the text word by word.”

If you do not fix the contract, you get the classic bug: the frontend expects the done field, the backend renames it to isDone, there are no tests, and the user keeps seeing “not done” for some reason. And that is still the best-case scenario.

To make the contract readable and stable, today we will establish three things:

  1. how and when to use Content-Type and Accept,
  2. how to design JSON request and response bodies (through DTOs),
  3. how to return errors consistently through a error envelope: { "error": { "code": "...", "message": "...", "fields": { ... } } }.

2. JSON API headers: Content-Type and Accept

In HTTP, headers often seem “secondary” to many people, because “the body is what matters.” But in reality, headers are like the label on a box during delivery. Sure, you can bring a parcel without a label, but then people will shake it, sniff it, and guess: “Is this really a mug, not a brick?” Headers help avoid guessing.

Content-Type: what it is and why it exists

Content-Type is the header about what you are sending in the body. If you send JSON in a request (for example, when creating a task), your request must honestly say: “there is JSON inside.”

A typical example:

POST /api/v1/tasks HTTP/1.1
Content-Type: application/json

{"title":"buy milk"}

If Content-Type is missing or says something else, the server has every moral right to say: “I do not know how to read this” — and return an error. In HTTP, this is most often status 415 Unsupported Media Type, but right now the number is less important than the contract idea itself.

An important nuance: if a request has no body (for example, many GET requests), then Content-Type is usually unnecessary. Do not send Content-Type: application/json “just in case”: that is like labeling an empty envelope “pie inside.”

Accept: what it is and why it exists

Accept is the header about what the client wants to receive. In a simple JSON API, the client usually says: “I expect application/json.”

Example:

GET /api/v1/tasks HTTP/1.1
Accept: application/json

If the client does not specify Accept, the server may still return JSON anyway (especially if the API is strictly JSON), but a proper contract likes explicitness.

An important psychological point: Content-Type is “what I brought you,” and Accept is “what I want from you.” These are two different roles, like “hand over documents” and “receive a receipt.”

Mini table for memory

To keep your brain from treating this as “header magic,” it helps to see a short table:

Header Who sets it What it is about When needed
Content-Type
body sender body format (for example JSON) when there is a body
Accept
client expected response format almost always, if the client cares about format

3. Request/response formats: why DTOs

When you design an API, it is very tempting to take your domain structure Task and just add json:"..." tags so that “everything works automatically.” This looks like a time saver, but usually it is a loan at 300% annual interest: a small joy now and a huge repair later.

The reason is simple: the domain model is responsible for the meaning and rules of the business domain, while the JSON contract is responsible for the external format of communication with the client. These are different responsibilities. If you glue them together, you start fearing changes to the domain because “I will break the API,” and fearing changes to the API because “I will break the domain.” You end up with an architectural sandwich made of fear.

That is why we introduce DTOs (Data Transfer Object): structures for JSON on the “outside.” The domain types live “inside” and do not need to know what JSON is.

DTOs for tasks

Let us imagine our educational “task tracker” app (a list of tasks). At the API level we want to:

  • create a task from a title,
  • get a task,
  • get a list of tasks.

Minimal and clear JSON fields:

  • id — number,
  • title — string,
  • done — boolean.

Let us create a DTO:

package main

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

And for a create-task request (usually the client does not send id — the server provides it):

package main

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

Pay attention: we intentionally do not use title,omitempty — because an “empty title” for a task is usually an error, and we want missing/empty values to show up explicitly during validation rather than “disappear.”

What JSON looks like without a server

We are not starting an HTTP server yet (that will be a separate topic), but we can already debug the JSON format “in vacuum.”

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	req := CreateTaskRequest{Title: "buy milk"}

	b, _ := json.MarshalIndent(req, "", "  ")
	fmt.Println(string(b))
	// {
	//   "title": "buy milk"
	// }
}

This is a simple but very useful technique: you literally see what you are promising to the client.

4. A unified error envelope: the error contract

Errors are where an API most often turns into a “zoo.” One endpoint returns {"error":"bad"}, another returns {"message":"oops"}, and a third gives plain text “panic: runtime error.” The client side then starts writing: “if there is an error field — it is an error, if there is a message field — that is also an error, if HTML arrived — well... probably also an error.”

To avoid this, we fix a single error format that is the same for the whole API. That is the error envelope.

The idea fits Go’s “errors are values” approach well: errors can be constructed, wrapped, classified, and displayed consistently.

Canonical format

The contract of our module:

{
  "error": {
    "code": "...",
    "message": "...",
    "fields": { "...": "..." }
  }
}

Rules:

  • error.code — machine code (for client logic),
  • error.message — short safe text (for humans),
  • error.fields — appears only for validation errors, as “field → problem.”

This is important: fields must not become a junk drawer for everything. The client will expect fields to mean “errors for specific input fields.”

Structures for the envelope in Go

We describe the envelope so that JSON consistently matches the contract.

package main

type APIError struct {
	Code    string            `json:"code"`
	Message string            `json:"message"`
	Fields  map[string]string `json:"fields,omitempty"`
}

type ErrorEnvelope struct {
	Error APIError `json:"error"`
}

Why is Fields with omitempty? Because in most errors fields is not needed, and we do not want to send "fields": {} all the time. Empty should remain empty.

Why both code and message are needed

Sometimes you want to keep only message, because “a human reads it.” But a computer reads too (client applications, scripts, integrations). If the client wants to distinguish not_found from validation, it should not parse a string and search for “not found” like it was a quest.

And sometimes you want to keep only code and remove message, because “let the frontend engineer write the texts.” That is also bad: you lose a unified UX, and different clients begin to show different messages. For a small educational API, it is more useful for the server to return both a machine code and a short message.

Here it is worth recalling an idea from Go practices: as soon as you make something recognizable and stable, you turn it into part of the API contract, and changing it later becomes painful. That is why we fix the error envelope as a “contract.”

5. Error examples: validation, not_found, internal

It is useful to “see” errors rather than only describe them in words. We will do that again through json.MarshalIndent so you can check the JSON shape without starting a server.

Validation error with fields

Typical scenario: the client sent an empty title.

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	env := ErrorEnvelope{
		Error: APIError{
			Code:    "validation",
			Message: "invalid request",
			Fields:  map[string]string{"title": "must not be empty"},
		},
	}

	b, _ := json.MarshalIndent(env, "", "  ")
	fmt.Println(string(b))
	// {
	//   "error": {
	//     "code": "validation",
	//     "message": "invalid request",
	//     "fields": {
	//       "title": "must not be empty"
	//     }
	//   }
	// }
}

Notice two things.

First, fields is a map, not an array of strings. That is convenient for the client: it can highlight a specific form field.

Second, message here is general (“invalid request”), while the details are in fields. This helps keep message from turning into a 12-volume novel.

Not found: without fields

When a resource is not found (for example, there is no task with such an id), fields is usually unnecessary: this is not an “input field error,” but the absence of an entity.

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	env := ErrorEnvelope{
		Error: APIError{
			Code:    "not_found",
			Message: "resource not found",
		},
	}

	b, _ := json.MarshalIndent(env, "", "  ")
	fmt.Println(string(b))
	// {
	//   "error": {
	//     "code": "not_found",
	//     "message": "resource not found"
	//   }
	// }
}

This is where omitempty shows its value: fields does not appear in JSON, and the client does not think: “Oh, fields exists, so this must be validation.”

Internal: a safe message

The most common beginner mistake in API work is to “just return err.Error() to the outside.” This can even seem convenient (“well, it really says what happened”), but in the real world this means you:

  • expose internal details (file paths, SQL, configs),
  • accidentally make the contract depend on the error text,
  • and sometimes leak secrets as well.

We use a stable message, for example "internal error". Details belong in logs, not in the contract. And that is exactly the boundary: what counts as part of the public API and what counts as internal implementation.

6. How to connect error envelope and Go errors

Now for an important point: the error envelope is a JSON shape at the boundary of the system, while inside you still have normal Go errors (error) that you return from functions, wrap, and check with errors.Is/errors.As (you already know this from previous days).

The idea is simple: inside the application you keep a rich error (with context), and on the way out (in HTTP) you turn it into one of the public classes:

  • validation → 400 + envelope with fields,
  • not_found → 404 + envelope without fields,
  • internal → 500 + envelope without internal details.

Why is that? Because “error as a value” lets you keep rich context for the program, but the public contract must remain stable and safe.

Mini dictionary of messages by code

To avoid writing texts “as it happens” in different places, it is useful to keep a small dictionary. This is not “perfect architecture,” just discipline.

package main

func messageFor(code string) string {
	switch code {
	case "validation":
		return "invalid request"
	case "not_found":
		return "resource not found"
	default:
		return "internal error"
	}
}

Yes, this looks like mini-i18n, just without localization. The main thing is stability.

Envelope constructor

To avoid writing ErrorEnvelope{Error: APIError{...}} every time, let us make a small function:

package main

func newErrorEnvelope(code string, fields map[string]string) ErrorEnvelope {
	return ErrorEnvelope{
		Error: APIError{
			Code:    code,
			Message: messageFor(code),
			Fields:  fields,
		},
	}
}

The point here is not “beauty,” but that the error contract becomes centralized. If errors are formed in one place, the chance of “accidentally changing the format” drops a lot.

7. A successful response and an error in the same style

Even without a server, we can show what a typical successful response and a typical error will look like. This helps keep in mind that an API has two equal branches: success and error. There is no API “without errors”; there is only API “with unexpected errors.”

Success: one task

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	task := TaskDTO{ID: 1, Title: "buy milk", Done: false}

	b, _ := json.MarshalIndent(task, "", "  ")
	fmt.Println(string(b))
	// {
	//   "id": 1,
	//   "title": "buy milk",
	//   "done": false
	// }
}

Error: invalid request

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	env := newErrorEnvelope("validation", map[string]string{
		"title": "must not be empty",
	})

	b, _ := json.MarshalIndent(env, "", "  ")
	fmt.Println(string(b))
	// {
	//   "error": {
	//     "code": "validation",
	//     "message": "invalid request",
	//     "fields": {
	//       "title": "must not be empty"
	//     }
	//   }
	// }
}

The error shape does not depend on the endpoint. That is the main value: the client can write one error handler and reuse it everywhere.

Where the JSON API contract lives: a diagram

Sometimes it helps to see a picture so the brain stops “chewing” this into abstractions.

flowchart LR
    C[Client] -->|HTTP request + Accept + JSON body| S[Server]
    S -->|2xx + JSON DTO| C
    S -->|4xx/5xx + JSON ErrorEnvelope| C

The essence of the diagram: the client always expects JSON (via Accept), and the server always responds either with DTO data or with an error envelope. “Always the same error shape” is not pedantry; it is what saves weeks of life during integrations.

8. Typical mistakes

Mistake #1: confusing Content-Type and Accept (or setting both “just in case”).
When a request has JSON body, Content-Type: application/json is mandatory, otherwise the server has to guess the format. Accept is the client’s request for a response format. If you set headers mechanically, it is easy to end up in a situation where the client “asks for JSON” but sends the body as “something unknown,” and then wonders why the server cannot read the data.

Mistake #2: returning different error formats on different endpoints.
This often starts innocently: “here I will return a string, there I will return an object.” A month later, the client already has three error handlers and one nervous tic. A unified error envelope is discipline that makes the API predictable. Once you have fixed it, treat it as a public contract, not as a “draft that can be improved.”

Mistake #3: turning message into a dump of details (or, conversely, keeping only code).
If message contains internal details ("sql: no rows", file paths, pieces of stack trace), you either reveal too much or accidentally make the error text part of the contract. If you keep only code, you get inconsistent client messages and lose a unified UX. The normal pair is code for logic and message for humans.

Mistake #4: using fields for the wrong purpose.
fields should mean “validation errors for specific input fields.” If you start stuffing anything into it (for example, "storage": "down"), the client will stop trusting the field and will be forced to write hacks. In the end, you lose the main advantage: the ability to highlight specific input problems for the user.

Mistake #5: leaking the internal error outside through err.Error().
It is useful to wrap, log, and analyze internal errors inside the server — in Go this is natural, because errors are values and can be structured. But outside, in the HTTP contract, you must return a stable and safe message. Otherwise, you “bake” the implementation into the public API and create obligations you never planned for.

1
タスク
Go SELF, レベル 56, レッスン 1
ロック未解除
JSON リクエスト
JSON リクエスト
1
タスク
Go SELF, レベル 56, レッスン 1
ロック未解除
エラー not_found
エラー not_found
1
タスク
Go SELF, レベル 56, レッスン 1
ロック未解除
エラーコンストラクタ
エラーコンストラクタ
1
タスク
Go SELF, レベル 56, レッスン 1
ロック未解除
作成の契約
作成の契約
コメント
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION