---
name: integrate-go-client
description: >
  Use the generated Go client in a Go service or CLI. Covers the package
  layout (client.go, operations.go, models.go, …), NewClient with options
  (WithBaseURL, WithServer, WithHTTPClient, WithRequestEditor for auth),
  context-first operation methods, optional parameters via <Op>Params and
  Ptr, APIResponse[T], typed per-operation errors (<Op>Error with StatusNNN
  fields) inspected with errors.As, oneOf/anyOf union structs, multipart,
  urlencoded and raw binary uploads with FilePart. Load when importing or
  using a generated go-mode package.
type: framework
library: openapi-client-generator
library_version: "3.0.0"
requires:
  - generate-client
sources:
  - "bazo/openapi-client-generator:src/modes/go/index.ts"
  - "bazo/openapi-client-generator:src/modes/go/operation.ts"
  - "bazo/openapi-client-generator:src/modes/go/runtime.ts"
  - "bazo/openapi-client-generator:src/converter/schema-to-go.ts"
  - "bazo/openapi-client-generator:src/modes/shared/response-cases-go.ts"
---

This skill builds on generate-client. Read it first for CLI usage.

# Integrate Go Client

## Setup

Generate into a directory inside your module; the output is one package directory named after `-n`:

```bash
npx openapi-client openapi.json internal/ -n PetStore -m go --package petstore
# → internal/PetStore/{client,runtime,errors,models,enums,unions,operations}.go, all `package petstore`
```

There are **no third-party dependencies** — only the standard library — and no `go.mod` is written;
import the package by its path in your module (`example.com/app/internal/PetStore`). Go **1.27+** is
required. The files are already gofmt-formatted and pass `go vet`.

Where to look, since the package is the API reference:

| File | Holds |
| --- | --- |
| `client.go` | `Client`, `NewClient`, the `With…` options, `Servers`, `DefaultBaseURL` |
| `operations.go` | one method per operation, plus its `<Op>Params` / `<Op>Result` types |
| `errors.go` | `APIError`, `DecodeError`, `UnionDecodeError`, and one `<Op>Error` per operation |
| `models.go` | structs and aliases for the spec's schemas |
| `enums.go` | string/int enum types with typed constants |
| `unions.go` | `oneOf`/`anyOf` union structs |
| `runtime.go` | `APIResponse[T]`, `NoContent`, `FilePart`, `Ptr`, and unexported plumbing |

Create a client:

```go
import (
	"context"
	"net/http"
	"time"

	petstore "example.com/app/internal/PetStore"
)

api, err := petstore.NewClient(
	petstore.WithBaseURL("https://api.example.com"), // or WithServer("staging"); default: DefaultBaseURL
	petstore.WithHTTPClient(&http.Client{Timeout: 10 * time.Second}),
	petstore.WithRequestEditor(func(ctx context.Context, req *http.Request) error {
		req.Header.Set("Authorization", "Bearer "+token)
		return nil
	}),
)
if err != nil {
	return err // no base URL (spec has no servers and no WithBaseURL), or unknown server name
}
```

`Client` is safe for concurrent use. Request editors run in order on every request just before it
is sent; returning an error aborts the call and that error is returned as-is.

## Core Patterns

### Call an operation

Every method takes `ctx` first and returns `(*APIResponse[T], error)`:

```go
res, err := api.GetTask(ctx, "task-1")
if err != nil {
	return err
}
task := res.Data          // Task
_ = res.StatusCode        // 200
_ = res.Header.Get("ETag")
```

Argument order is fixed: `ctx`, path parameters (in path order), required query/header parameters,
`body` (when the operation has one), then `params *<Op>Params` holding every OPTIONAL query/header
parameter as a pointer field. Pass `nil` when you set none:

```go
list, err := api.ListTasks(ctx, &petstore.ListTasksParams{
	Page:   petstore.Ptr(2),
	Status: petstore.Ptr(petstore.ListTasksStatusParamDone),
})
list, err = api.ListTasks(ctx, nil)
```

`Ptr` exists for exactly this: Go cannot take the address of a literal.

### Send a body

A required body is a value, an optional one a pointer (`nil` sends no body):

```go
created, err := api.CreateTask(ctx, petstore.CreateTaskRequest{
	Title:       "Build feature",
	Status:      petstore.CreateTaskRequestStatusTodo,
	Description: petstore.Ptr("optional fields are pointers"),
})
patched, err := api.PatchTask(ctx, "task-1", &petstore.UpdateTaskRequest{Title: petstore.Ptr("Renamed")})
```

### Model fields

| Spec | Go field | JSON |
| --- | --- | --- |
| required | `T` | always sent |
| required + nullable | `*T` (`nil` → `null`) | always sent, key present |
| optional | `*T` | omitted when `nil` (`omitempty`) |
| optional slice / map / free-form | `[]T` / `map[string]T` / `json.RawMessage` | omitted when `nil` (`omitzero`) |

Formats: `date-time` → `time.Time`, `int32`/`int64` → `int32`/`int64`, `integer` → `int`,
`float` → `float32`, `number` → `float64`, `byte` → `[]byte`; `uuid`, `date`, `uri`, `email` stay
`string`. A free-form value (`{}`) is `json.RawMessage`.

Decoding is **strict** where the spec is: a response missing a required key fails with a
`*DecodeError`, and an enum value the spec does not declare is rejected. Unknown extra keys are
ignored.

For an API that adds enum values without notice (App Store Connect does), generate with
`--lenient-enums`: an undeclared value then decodes and is kept verbatim (it round-trips on
`Marshal`), so check `Valid()` before switching on it. Union trial decoding still prefers the branch
whose enum values are all declared, so a JSON:API `type` tag keeps picking the right branch; only
when no branch declares the value does the first branch that decodes win.

```go
if !app.Attributes.Platform.Valid() { /* a value this client was not generated with */ }
```

### Enums

```go
petstore.TaskStatusDone          // typed constant: <Type><Value>
petstore.TaskStatus("done").Valid()
```

Values that fold onto the same identifier (`Male`, `male`, `MALE`) get `_` suffixes
(`GenderMale`, `GenderMale_`, `GenderMale__`), each keeping its own wire value. Always use the
generated constant; never assume a spelling.

### Handle errors

Every non-2xx response is returned as that operation's own `*<Op>Error`. It embeds `*APIError`
(status, raw body, headers, URL) and has one typed pointer field per documented error status —
`Status404`, `Status4XX` for a range, `Default` for the spec's `default` response. The field
matching the status is set when its body decoded:

```go
_, err := api.GetTask(ctx, id)
var getErr *petstore.GetTaskError
switch {
case err == nil:
	// success
case errors.As(err, &getErr) && getErr.Status404 != nil:
	log.Printf("not found: %s", getErr.Status404.Message) // typed ErrorResponse
case errors.As(err, &getErr):
	log.Printf("HTTP %d: %s", getErr.StatusCode, getErr.Body) // undocumented status, or DecodeErr set
default:
	return err // transport, context, request-editor or encoding error — not an HTTP response
}
```

For code that handles any operation's error, match the shared type — every `<Op>Error` unwraps to
it:

```go
var apiErr *petstore.APIError
if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusUnauthorized { … }
```

Other error types:

- `*DecodeError` — a 2xx response whose body did not decode (embeds `*APIError`, `Unwrap` gives the
  JSON error).
- `APIError.DecodeErr` — a DOCUMENTED error status whose body did not decode (e.g. an HTML error
  page); the `StatusNNN` field is then `nil` and the raw body is still in `Body`.
- `*UnionDecodeError` — no branch of a union matched; `Errs` holds each branch's failure.

### Multiple success types

When the 2xx statuses carry different body types, `Data` is an `<Op>Result` with one field per
status; the one matching `StatusCode` is set:

```go
res, err := api.MultiStatus(ctx)
switch {
case res.Data.Status200 != nil: …
case res.Data.Status201 != nil: …
}
```

An operation with no success body returns `APIResponse[NoContent]`.

## Union (`oneOf` / `anyOf`) schemas

A union whose every branch is a named object schema becomes a struct with one pointer field per
branch; exactly one is set. Build one with the generated constructor, read it by checking fields:

```go
_, err := api.CreateNote(ctx, petstore.NoteBodyFromTextNote(petstore.TextNote{Text: "hi", WordCount: 1}))

note := res.Data // NoteBody
switch {
case note.TextNote != nil:
	fmt.Println(note.TextNote.Text)
case note.LinkNote != nil:
	fmt.Println(note.LinkNote.URL)
}
```

On the wire the value is the **bare branch object**. Decoding uses the spec's discriminator when
it declares one; otherwise (or on an unknown tag) it tries each branch in order and takes the
first that decodes — which works because models reject a missing required key and enums reject
unknown values. Encoding a union with no branch set is an error. Any other union (primitive
branches, nested unions, nullable branches) is `json.RawMessage`.

### Polymorphic base schemas (discriminator without `oneOf`)

The OpenAPI 3.0 idiom of a base schema carrying a `discriminator.mapping`, whose subtypes are
`allOf: [$ref Base, {...}]`, is generated as a union of the MAPPED subtypes, even though the spec
never writes a `oneOf`. Every operation returning the base returns the union, so a subtype's own
fields are never lost:

```go
res, err := api.ListClients(ctx, siteID, nil)
for _, c := range res.Data.Data { // []ClientOverview, a union
	switch {
	case c.WiredClientOverview != nil:
		fmt.Println(c.WiredClientOverview.MacAddress)
	case c.WirelessClientOverview != nil:
		fmt.Println(c.WirelessClientOverview.UplinkDeviceID)
	}
}
```

The tag picks the branch. An unknown tag falls back to trial decoding. The base stays a plain struct
when its mapping names a schema that does not exist, or when it backs a form body. A `required` list
written beside an `allOf` binds the fields its members declare, so those fields are value types, not
pointers.

## File uploads and form bodies

`FilePart` is the file type everywhere:

```go
f, _ := os.Open("report.pdf")
defer f.Close()
part := petstore.FilePart{Filename: "report.pdf", ContentType: "application/pdf", Content: f}
// or from memory: petstore.NewFilePart("note.txt", "text/plain", []byte("hello"))

_, err := api.UploadAttachment(ctx, petstore.UploadAttachmentMultipartFormDataRequest{
	File:  part,
	Title: "Q3",
	Tags:  []string{"a", "b"}, // repeated parts named "tags"
})
```

- **multipart/form-data**: each field is one part under its spec name; an array of scalars is
  repeated parts, an object (or array of objects) is one part holding JSON text; `nil` values and
  `nil` array elements send nothing. A union body sends the set branch's fields.
- **application/x-www-form-urlencoded**: same rules as `k=v` pairs, in declaration order.
- **raw binary** (`application/octet-stream`, `image/*`, …): the body parameter IS a `FilePart`;
  its `Content` is streamed as the request body.
- **text** (`text/*` with a `string` schema): the body is a `string`, sent verbatim under the
  declared media type — never JSON-encoded.

`FilePart.Content` is read once, when the request is sent — create a fresh reader per call.

## Wire names that are not Go identifiers

Field names are exported PascalCase with Go initialisms (`user_id` → `UserID`, `a.b` → `AB`,
`2fa` → `N2Fa`); the JSON tag keeps the wire name. A key a struct tag cannot spell (an emoji, a
quote, a newline) is tagged `json:"-"` and carried by the model's own `MarshalJSON` /
`UnmarshalJSON` — it still round-trips. Query, header and form names are literal strings and never
folded. Two fields folding onto one identifier is a generation error; rename one in the spec.

## Common Mistakes

### CRITICAL Treating a documented error as a transport error

Wrong:

```go
if _, err := api.GetTask(ctx, id); err != nil {
	return fmt.Errorf("network problem: %w", err)
}
```

Correct:

```go
var getErr *petstore.GetTaskError
if errors.As(err, &getErr) {
	// the server answered; inspect getErr.StatusCode / getErr.Status404
}
```

A non-nil `err` covers both "the server said no" and "no response at all". Only the former is an
`*<Op>Error` / `*APIError`.

### HIGH Comparing the error type directly

Wrong: `if e, ok := err.(*petstore.APIError); ok { … }` — the returned error is `*GetTaskError`,
which only UNWRAPS to `*APIError`. Use `errors.As`.

### HIGH Building a union struct by hand with two fields set

Wrong: `petstore.NoteBody{TextNote: &t, LinkNote: &l}` — only the first set field is sent. Use a
`<Union>From<Branch>` constructor.

### HIGH Reusing a FilePart across calls

Its `Content` reader is drained by the first request; the second sends an empty file. Build the
`FilePart` (or re-open the file) per call.

### MEDIUM Expecting to send an explicit null for an optional field

An optional field that is `nil` is omitted, not sent as `null`. Only required+nullable fields send
`null`. `encoding/json` also matches incoming keys case-insensitively.

### HIGH Editing the generated files

They carry `// Code generated … DO NOT EDIT.` and are overwritten on the next run. Add methods in
another file of the same package, or wrap the client.

See also: generate-client/SKILL.md — CLI usage for regenerating the client
