> [Agent navigation index](/llms.txt)

# OpenAPI client generation

Generate clients from external API specifications. To serve a document and Swagger UI for your own API routes, see [API documentation](/docs/api-documentation.md).

Brix generates Zod schemas and typed API contracts from Swagger/OpenAPI 2.0 and OpenAPI 3.0/3.1 definitions. Generated contracts are universal: they can be consumed from a Brix application, a Node service, a worker, a library, or an external browser client with the standard Fetch API.

## Generate one specification

```sh
brix openapi generate ./openapi/catalog.yaml --out src/generated/catalog-api --name catalog

```

The input can be a local file or an HTTP(S) URL. External references are resolved and bundled. The example assumes the application owns `openapi/catalog.yaml`.

The output directory is completely generated. Every successful run replaces all of its contents, including unexpected files. Never store handwritten code or unrelated tool output there. Brix rejects paths outside the project and symbolic-link traversal. The first run requires a new or empty directory; afterwards its `.brix-openapi.json` marks it as generated output. Brix refuses to replace a non-empty directory without that file, such as a mistyped `--out src`, or a file at the output path, and `--dry-run` reports the same refusal.

After the command succeeds, import contracts and schema types from
`src/generated/catalog-api/index.ts`; do not implement a Brix server route merely to call this
external API. The [consumption example](#consume-a-generated-contract) shows the resulting workflow.

## Configure multiple definitions

Create `brix.openapi.ts` at the owning project root:

```ts
import { defineBrixOpenApiConfig } from "brix/config";

export default defineBrixOpenApiConfig({
  name: "commerce",
  out: "src/generated/commerce-api",
  definitions: {
    catalog: "openapi/catalog.yaml",
    accounts: "openapi/accounts.json",
  },
  groupBy: "tag",
  strict: true,
});

```

`name`, `out`, and at least one definition are required. `groupBy` (`"tag"` by default, or
`"none"`) and `strict` are optional; the `--group-by` flag overrides `groupBy`, and either `--strict`
or `strict: true` enables strict mode.

```sh
brix openapi generate
brix openapi generate --config config/apis.ts

```

Without arguments, the command reads `brix.openapi.ts`; `--config` selects another file. Definition paths and `out` are relative to the selected project root, not the config directory. A definition may also be an HTTP(S) URL. Within a workspace, run `brix openapi#storefront generate` for the owning member; the bare command fails at the workspace root.

## Import the public generated root

The configured name determines the aggregate export. A single specification named `catalog` exposes `catalogContracts`; multiple definitions named `commerce` expose `commerceContracts` with definition namespaces.

```ts
import { catalogContracts, type CatalogUser } from "#/generated/catalog-api/index.ts";

```

The exact members depend on the specification. For example, a `products` tag with a `getProduct` operation and a `User` schema produces access through:

```ts
catalogContracts.products.getProduct;
catalogContracts.schemas.catalogUserSchema;

```

Contracts are grouped by their first tag by default. `--group-by none` uses a nested `contracts` group instead. Multi-definition output adds definition prefixes and collision-safe namespaces. Repeated adjacent prefixes are collapsed rather than producing names such as `CommerceCatalogCatalog`.

Import only the generated top-level `index.ts`, through the project's `#/` alias inside a Brix application or a relative path elsewhere. Internal module paths are implementation details and can change as the specification evolves.

## Consume a generated contract

Generated modules import `brix/contracts` and `brix/zod`. They do not require Hono, a server setup file, route discovery, or a running Brix application.

For the illustrative `getProduct` operation above, whose path declares `productId`:

```ts
import { createApiClient } from "brix/contracts";
import { catalogContracts } from "#/generated/catalog-api/index.ts";

const client = createApiClient({ baseUrl: "https://catalog.example.com/api/v1" });
const result = await client.execute(catalogContracts.products.getProduct, {
  params: { productId: "sku-123" },
});

if (result.isOk()) console.log(result.value);
else console.error(result.error.kind);

```

Set `baseUrl` explicitly and include any path prefix from the selected OpenAPI server URL. Configure credentials and required header/cookie values at the request/client boundary; the generator does not implement authentication for you. See [API clients](/docs/api-routes.md) and [caching](/docs/caching.md).

## Review and enforce drift

For a configured project, preview changes, then verify that committed output matches:

```sh
brix openapi generate --dry-run
brix openapi generate --check

```

For the single-specification command earlier, retain its input, output, and name on every run:

```sh
brix openapi generate ./openapi/catalog.yaml --out src/generated/catalog-api --name catalog --check

```

Generation is deterministic. The `.brix-openapi.json` manifest records generated output so `--check`
fails with `Generated OpenAPI contracts are out of date` on changed, missing, or unexpected files
without writing. `--dry-run` and `--check` cannot be combined. `brix check` does not regenerate or
compare OpenAPI output, so add `brix openapi generate --check` to CI with the same input and options as
local generation. For a remote URL input, `--check` also detects upstream specification changes.
Review specification and generated-code changes together.

## Upgrade generated clients

Brix owns the generator version, so a Brix upgrade can change generated output even when the
specification does not. After upgrading, rerun the existing generation command, then review the
diff and run `brix check` and your tests:

- Compare numeric schemas, including bounds and `multipleOf` on formatted numbers, and enum wire
  values, including titled OpenAPI 3.1 `oneOf`/`anyOf` const members that may become named enums.
- Check dictionaries (`z.record`/`z.partialRecord`), open objects (`z.looseObject`), optional keys,
  and additional properties against real payloads.
- Confirm local `$ref` values, including escaped `/` or `~` segments, still resolve to the intended
  schemas.
- Read every new diagnostic. Keep validation enabled; strict mode turns warnings into failures.

Check the actual generated exports rather than assuming an upstream plugin's example is Brix's
output. Never hand-edit generated output. The [upgrade guide](/docs/releases-upgrades.md) lists
consumer actions for each Brix release.

## Serialization boundaries

Brix fails operations it cannot represent faithfully instead of silently altering their HTTP behavior:

- Request bodies must have one `application/json` or `application/x-www-form-urlencoded` representation. Forms generate `bodyEncoding: "form-urlencoded"` and require an explicit object schema with explicit string properties (required or optional, including string enums and constraints). Swagger 2 `formData` is supported. Nested, array, numeric, nullable, unknown, binary, dynamic, and composed form schemas are rejected, as are nonempty property `encoding` maps. `additionalProperties` must be absent or false. Schema `$ref` values may have documentation-only siblings; validation or structural siblings are rejected because generated schemas do not preserve their intersection. Form fields are not coerced like query values.
- GET bodies, unsupported methods, unsupported success bodies, and complex or reserved query serialization are rejected.
- Path placeholders must occupy whole segments, such as `/files/{id}`, with names matching `[A-Za-z_][\w-]*`. Embedded placeholders such as `/files/{name}.{ext}` or `/files/prefix-{id}` are rejected. Path parameters support only `simple` serialization (the default); `matrix` and `label` styles fail generation even without `--strict`. Use a hand-authored client for unsupported wire formats.
- Colliding tag namespaces fail generation.
- Numeric and boolean query fields accept either the typed value or its URL string form, including repeated strings for arrays, and are decoded before validation so parsed output contains numbers and booleans. Only own query keys are decoded, so names such as `toString` are never read from `Object.prototype`.
- `integer` schemas, including `format: int64`, generate `z.int()` JSON numbers rather than `bigint`: JSON has no bigint, so bigint bodies could not be sent and parsed responses could not be re-serialized. Values beyond `Number.MAX_SAFE_INTEGER` fail validation instead of silently losing precision; use a hand-authored string schema for APIs that transmit larger identifiers.
- OpenAPI `2XX`, bodyless, and `default` success responses remain represented in the runtime response union. A `default` response schema therefore validates successful responses and produces its own warning; for error statuses, `ApiRequestError.data` remains unknown. Status ranges are matched in any case and named in lower case, so a `2XX` response generates `<operation>Status2xxSchema`.

Authentication requirements, header/cookie parameters, path-parameter schemas, error-response schemas, and optional bodies produce warnings where the current runtime does not own the complete semantics. `--strict` turns every warning into a failure. Investigate each warning; do not simply remove strict mode to accept an incorrect client.

Keep handwritten endpoint adapters outside the generated directory when an API needs behavior that cannot be represented by the contract runtime. The generated schemas describe the supported wire boundary, not arbitrary application validation or server implementations.
