---
name: integrate-full-client
description: >
  Use the generated full-mode TypeScript client in a web application.
  Covers peer dependencies (zod, wretch, @tanstack/react-query), client
  class instantiation with baseUrl and QueryClient, React Query useQuery
  and useMutation hooks, Wretch HTTP configuration via onHttpConfigure,
  ApiResponse<T> type, query invalidation, and GenericWretchError. Load
  when importing or using a generated full-mode client file.
type: framework
library: openapi-client-generator
library_version: "3.0.0"
requires:
  - generate-client
sources:
  - "bazo/openapi-client-generator:src/modes/full/index.ts"
  - "bazo/openapi-client-generator:src/modes/full/query.ts"
  - "bazo/openapi-client-generator:src/modes/full/mutation.ts"
---

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

# Integrate Full Client

## Setup

Install peer dependencies required by the generated file:

```bash
npm install zod wretch @tanstack/react-query
```

The generated validators are Zod 4 (`z.email()`, `z.iso.datetime()`, `z.int()`, `z.strictObject()`), so `zod` must be >= 4.

Instantiate the client:

```typescript
import { QueryClient } from "@tanstack/react-query";
import { MyClient } from "./generated/MyClient";

const queryClient = new QueryClient();
const api = new MyClient("https://api.example.com", queryClient);
```

The constructor signature is:

```typescript
constructor(
  baseUrl: string,
  queryClient: QueryClient,
  options?: RequestInit,
  onHttpConfigure?: (w: Http) => Http
)
```

## Core Patterns

### Use a generated query hook in a React component

```typescript
function TaskList() {
  const { data, isLoading } = api.listTasks.useQuery({ page: 1, limit: 10 });

  if (isLoading) return <div>Loading...</div>;
  return <div>{data?.data.items.map(t => <div key={t.id}>{t.title}</div>)}</div>;
}
```

Each query operation exposes `.useQuery(params, options?)` which returns a standard React Query result extended with `.key` (the query key) and `.invalidate()` (shortcut for `queryClient.invalidateQueries`).

### Use a generated mutation hook

```typescript
function CreateTask() {
  const { mutate, isPending } = api.createTask.useMutation({
    onSuccess: () => api.listTasks.useQuery.invalidate?.(),
  });

  return (
    <button onClick={() => mutate({ body: { title: "New task", status: "todo" } })} disabled={isPending}>
      Create
    </button>
  );
}
```

Each mutation operation exposes `.useMutation(options?)`.

### Use the query function directly (outside React)

```typescript
const result = await api.listTasks.query({ page: 1, limit: 10 });
console.log(result.data); // typed response body
console.log(result.status); // HTTP status code
```

Every operation also exposes a `.query()` or `.mutation()` function for non-React usage.

### Suspense members (query endpoints)

Query operations additionally expose a Suspense-oriented surface —
`.queryOptions(params?)`, `.useSuspenseQuery(params?, options?)`, `.fetch()`,
and an emitted `export class ApiStatusError` — that throws documented non-2xx
responses instead of resolving them into the status union (documented by an exact
status, a `4XX`-style range, or `default`, looked up in that order). Every documented body is
validated strictly: `ApiStatusError.data` is the typed envelope, and a body that breaks its schema
(an HTML 500, an extra key under a strict schema) rejects with `ResponseValidationError` — `status`,
`headers`, `url`, raw `body`, ZodError/SyntaxError as `cause` — instead. These share the
same cache key as the legacy `.useQuery`. Use them to drive skeletons and error
boundaries so a UI never shows an empty state while loading. Wiring them
(loaders, `useSuspenseQueries`, `QueryErrorResetBoundary`, 404→`notFound()`,
search-param pagination) is covered in its own skill — see below.

### Configure HTTP with auth headers

```typescript
const api = new MyClient(
  "https://api.example.com",
  queryClient,
  undefined,
  (http) => http.auth(`Bearer ${token}`)
);
```

The `onHttpConfigure` callback receives a Wretch instance and must return one. Use it to add auth, interceptors, or middleware.

### Header parameters

A header the spec declares on an operation (`in: header`) is an ordinary entry of that operation's
`params`, keyed by the identifier form of its name (`x-install-id` → `xInstallId`, `X-Request-ID` → `XRequestID`), typed and
validated like a path or query param:

```typescript
await api.followPushTopic.mutation({ topic: "occasion:123", xInstallId: installId });
await api.listPushTopics.query({ xInstallId: installId });
```

It is sent under its wire name. An optional header left out of the call is not sent at all (never as
the string `"undefined"`). An array is sent comma-joined, OpenAPI's `style: simple`. A header that is
the same on every request (auth, a device id) belongs in `onHttpConfigure`, not in each call.

### Path and array query parameters

Path parameters are percent-encoded (`encodeURIComponent`), so an id containing `/`, `?` or `#`
cannot reshape the URL — pass the raw value, never a pre-encoded one. An array query parameter is
sent as the spec says: by default the key repeats (`filter[id]=1&filter[id]=2`); one declared
`explode: false` (App Store Connect's `include` / `fields[…]`) is sent once, comma-joined
(`include=a,b`), and an empty array sends no key at all.

```typescript
await api.appsGetInstance.query({ id: appId, include: ["appInfos", "appStoreVersions"] });
```

## File uploads (multipart)

An operation whose request body is `multipart/form-data` takes `BinaryInput` for each `format: binary` field. The client builds the `FormData` for you — pass plain values in `body`:

```typescript
const input = document.querySelector<HTMLInputElement>("#file")!;
await api.uploadTaskAttachment.mutation({
  taskId: "42",
  body: {
    file: input.files![0], // File
    description: "Q3 invoice",
  },
});
```

### React Native / Expo

`BinaryInput` is `Blob | File | ReactNativeFilePart` — one generated client is meant to serve a web app and a React Native app, so it accepts whichever file shape the runtime it is running in can actually send. **On React Native you must pass `{ uri, name, type }`, not a `Blob`:**

```typescript
await api.uploadTaskAttachment.mutation({
  taskId: "42",
  body: {
    file: { uri: asset.uri, name: "scan.png", type: "image/png" },
    description: "Q3 invoice",
  },
});
```

A `Blob` — including the one `await fetch(uri).then((r) => r.blob())` returns, which several upload guides recommend — is **silently dropped** from a multipart body by React Native. Its `FormData.getParts()` spreads each value and the native layer looks for a `uri`, `string` or `base64` key; a Blob exposes only `_data`, matches none of them, and RN discards the part ("Nothing in the data payload… Ignore and treat it as if it were null"). The request still succeeds and the server reports a missing file. A Blob also has no `.name`, so no `filename` would be sent even if the part survived. Passing one is rejected up front by validation rather than producing that, which is the point of the type.

The part shape is validated strictly: a string `uri`, and no key outside `uri`, `name` and `type` — the exact three React Native reads. If your picker hands you `{ uri, name, size, mimeType }`, build the part explicitly rather than spreading it. The strictness is deliberate: on a `oneOf`/`anyOf` multipart body the field kinds are not statically known, and a looser test would send an ordinary JSON object that happened to carry a `uri` string as a file part.

Two things are unchanged on React Native: never set `Content-Type` by hand (RN sets `multipart/form-data` **with the boundary** when the body is a `FormData`; supplying the header replaces it with a boundary-less value most servers cannot parse), and a raw binary body may be a `Blob` there — only the multipart part path needs `{ uri }`.

Field encoding rules: scalars become one part; arrays of scalars become repeated parts sharing the field name (e.g. `tags`, `tags`, never `tags[0]`); objects and arrays of objects become a single part containing their JSON as a plain **text field** — no filename, and no `Content-Type: application/json` (browser `FormData` cannot set a part content type without turning the part into a file, and a file-classified part is what the swift/kotlin/php clients never send); `undefined` and `null` fields are omitted entirely. A field whose spec name is not a valid JS identifier (`file-name`) keeps that exact wire name and is read off `body` by that name. A composed (`allOf`) body contributes every branch's properties. A `oneOf`/`anyOf` body is typed as the union of its branches and sends the fields of whichever branch you actually pass — the client reads the value **you** passed at request time (not the Zod-parsed copy: `z.union` returns the first option that validates, which would truncate a body built from a wider branch, and strip an all-optional branch's sibling to nothing), so the parts are identical to the ones the swift, kotlin and php clients send for the same branch, wire names, repeated array parts and single JSON parts included. Validation still runs; it just no longer decides the wire form. Only wire names the spec declares on some branch are sent, so an object typed wider than the branch does not leak its extra properties into the request. A union body's branches must each have a field set of their own: if any branch has none — a primitive, an array, or an object with no declared properties — the whole body falls back to sending no parts at all, in every mode alike. The same fallback applies to a union the Kotlin generator cannot express as a sealed class (most reachably when a schema named `<UnionName>Serializer` already exists, but also when the union carries a sibling `enum` or is an `anyOf` of one type plus `null`), because Kotlin then has no sum type to dispatch on and the five modes only stay in step by all sending nothing. A `oneOf`/`anyOf` **urlencoded** body dispatches on the branch in exactly the same way, sending that branch's own fields as `k=v` pairs — an array field as repeated keys, an object-valued field as one JSON-encoded value — and it takes the same fallback, with the same explanatory comment, only when the branches cannot be described. A SINGLE-variant `anyOf` (`anyOf: [$ref Only]`) is not a union at all: it is simply its branch, typed and sent as that object in every mode. A schema carrying BOTH top-level `properties` and an `allOf` means "an object with those properties that ALSO satisfies every member of the allOf": the generator folds the properties in as one more `allOf` member, so they appear in the generated type and on the wire alongside the composed base's fields (they used to be dropped from the type while the form walk still emitted a part for them). The folded properties go LAST, so they WIN any name they share with the base: a sibling `count: { type: string }` over a base's `count: { type: integer }` types the field `string`, the reading the swift, kotlin and php clients have always taken. The base's own copy is SUBTRACTED from the emitted validator for that name (`z.intersection(OverrideBase.omit({ count: true }), z.object({ count: z.string() }))`), because intersecting the two demanded the value be a number AND a string — a validator no payload could satisfy, and one the same spec avoided entirely if the base was written inline instead of behind a `$ref`. A schema carrying BOTH top-level `properties` and a `oneOf` means "an object with those properties that additionally satisfies one of the branches": the generator distributes the properties over every branch, so the body types as `({ album: string } & Song) | ({ album: string } & Podcast)` and each alternative carries the shared fields. All five modes distribute identically, so the parts on the wire are the same from each. Because distribution reaches response schemas too, the shared properties are now required in every branch, so a response omitting one fails validation where it previously passed — spec-faithful, but stricter than before. A discriminated union whose branches are `allOf` compositions, or whose discriminator property is an unconstrained `string`, cannot be a `z.discriminatedUnion`: Zod only accepts plain object options whose discriminator narrows to literals, and handing it anything else fails `tsc` and throws on the first `parse`. Those unions are emitted as a `z.union` whose options are **tag-constrained** — each branch is paired with the literal its `discriminator.mapping` demands (`z.intersection(SystemEvent, z.object({ kind: z.literal("system") }))`) and the bare branches follow as a trailing fallback. So a recognised tag selects its branch no matter what order the branches are declared in, and an unrecognised or absent tag falls through to trial decoding — the same answer the kotlin client gives for the same bytes. A `mapping` is OPTIONAL: absent one, OpenAPI says the tag is matched against the branches' own SCHEMA names, and the tag constraint is built from those instead (`z.literal("SystemEvent")`) — the rule the swift and kotlin clients already applied, so all four typed modes now pick the same branch for a mapping-less discriminator. Previously the TS modes refused without a mapping and fell back to declaration order, which answered with the narrow branch (and stripped the fields only the wide one declares) where swift and kotlin answered with the wide one. An ANONYMOUS branch — one the spec spells inline, with no schema name — has no name to answer to, so it is never selected by tag and stays reachable only through trial decoding. A `discriminator` declared on an **`anyOf`** is read exactly the same way — OpenAPI allows one on all three composition keywords, and the swift and kotlin clients have always honoured it there, so a bare `z.union` answered with the narrow branch (dropping the fields only the wide one declares) where they answered with the wide one. The bare options stay behind the tag-constrained ones for the same reason as on a `oneOf`, and it matters more here: `anyOf` permits a value to satisfy several branches, and a tag no branch claims still has to reach trial decoding. Because the tag constraint is an `z.intersection(Branch, z.object({ kind: z.literal(...) }))`, the tag is present in the PARSED data even when the branch schema itself never declares that property: `{"petType":"Cat","lives":9}` comes back as `{ lives: 9, petType: "Cat" }` here, while the swift and kotlin clients drop it (their branch types have no such field), so the returned object differs across modes for that shape. If you control the spec, prefer OpenAPI 3.1's `kind: { type: string, const: "system" }`: a STRING `const` is treated as a one-value enum, which restores a real `z.discriminatedUnion` and with it TypeScript narrowing (`if (e.kind === "system") e.severity`). Only a string narrows to an `enum`, because a `String`-raw Swift enum cannot decode a bare `true` or `null`. A boolean, integer or `null` `const` is still PINNED, just as a literal rather than an enum: `z.literal(true)`, `z.literal(42)`, `z.null()`. That matters beyond precision — a bare `{ const: null }` names no type, so it used to fall through to `z.unknown()`, which accepts the key being ABSENT and quietly loosened a REQUIRED field that the swift and kotlin clients both reject. Omitting the whole `body` on an operation with an optional multipart body still sends a well-formed (empty) `FormData`, not a bodyless request.

Form-urlencoded bodies (`application/x-www-form-urlencoded`) take a plain object; they are serialized field-by-field under the same rules (repeated keys for arrays, JSON text for objects, `undefined`/`null` omitted, and a `format: binary` field treated as a plain string — a urlencoded body cannot carry a file). Omitting an optional urlencoded `body` sends a well-formed empty urlencoded request. Raw binary bodies (`application/octet-stream`, `image/*`, …) take a single `BinaryInput` — here a `Blob` is fine on React Native too, since RN maps a Blob body natively (and a `{ uri }` works as well, which it resolves by reading that URI):

```typescript
await api.requestToken.mutation({ body: { grantType: "password", clientId: "abc" } });
await api.uploadRawBlob.mutation({ body: new Blob([bytes]) });
// A `text/*` body with a `string` schema is the string itself, sent under its media type:
await api.renderMarkdownRaw.mutation({ body: "# Title" });
```

Note: an **inline** (non-`$ref`) request body or parameter schema is spelled out as a structural type, so it is fully typed without needing a named schema — e.g. an inline multipart body comes out as `body: { file: BinaryInput; title: string; tags?: Array<string>; metadata?: { source?: string } }`, with `format: binary` fields typed `BinaryInput`. A `$ref`'d body still types as `body: z.infer<typeof ReportUpload>`.

## Common Mistakes

### CRITICAL Missing peer dependencies

Wrong:

```bash
npm install zod
# Generated file fails: Cannot find module 'wretch'
```

Correct:

```bash
npm install zod wretch @tanstack/react-query
```

The generated full-mode file imports from `zod`, `wretch`, `wretch/addons/queryString`, and `@tanstack/react-query`. All four must be installed in the consuming project.

Source: src/modes/full/index.ts generateImports

### CRITICAL Instantiating client without QueryClient

Wrong:

```typescript
const api = new MyClient("https://api.example.com");
```

Correct:

```typescript
import { QueryClient } from "@tanstack/react-query";
const queryClient = new QueryClient();
const api = new MyClient("https://api.example.com", queryClient);
```

The constructor requires both `baseUrl` and a `QueryClient` instance. The client uses a Proxy to lazily bind operations to the HTTP instance and QueryClient — without the QueryClient, hooks will fail at runtime.

Source: src/modes/full/index.ts generateClient

### HIGH Editing the generated file directly

Wrong:

```typescript
// Manually adding a custom method to MyClient.ts
export class MyClient {
  // ...generated code...
  async customMethod() { /* hand-written */ }
}
```

Correct:

```typescript
// Extend or wrap the generated client in a separate file
import { MyClient } from "./generated/MyClient";

class ExtendedClient extends MyClient {
  async customMethod() { /* hand-written */ }
}
```

The generated output is meant to be regenerated from the spec. Manual edits are overwritten on the next generation run.

Source: maintainer interview

See also: generate-client/SKILL.md — CLI usage for regenerating the client
See also: integrate-suspense-queries/SKILL.md — wiring queryOptions/useSuspenseQuery/ApiStatusError into Suspense + error boundaries

## Recursive schemas

A schema that refers to itself (`Repository.parent: Repository`) or sits in a cycle (`A → B → A`)
is declared with Zod 4 getters, so the reference is read after every member of the cycle exists and
`z.infer` stays fully typed:

```typescript
export const Repository = z.object({ id: z.int().optional(), get parent() { return Repository.optional(); } });
export type Repository = z.infer<typeof Repository>;
```

Only properties that reach back into their own cycle become getters; everything else is unchanged.

## Parameter names that are reserved words

A parameter keeps its spec name as the key of `params` (`{ private: true }`), even when that name is
a reserved word; the client binds it to a legal local (`private: private_`) internally.
