CLI

axil generate client

axil generate client turns an OpenAPI 3.x JSON document into one dependency-free TypeScript file with schema types, one typed method per operation, ApiError and bearer-token support.

8 min readUpdated DocumentationEdit this page
On this page12

axil generate client reads an OpenAPI 3.x document and writes one dependency-free TypeScript file: a type for every schema, one typed method per operation, an ApiError class and bearer-token support. Use it for frontends, other services and tests. With an AxilJS backend, the document comes from app.serveOpenAPI(), so the client always matches the routes and validate() schemas the server actually has.

Note

New in 0.4.0. The generator works with any OpenAPI 3.x JSON document, not only ones produced by AxilJS.

Terminal
❯axil generate client # from http://localhost:<PORT>/openapi.json
❯axil generate client --from ./openapi.json
❯axil g client --from https://api.example.com/openapi.json --out src/clients/billing.ts --name BillingClient

Options

OptionDefaultDescription
--from <url|file>http://localhost:<PORT>/openapi.json, with PORT from .env, else 3000An http(s) URL, fetched with a 10 second timeout, or a local JSON file
--out <file>src/api-client.tsOutput file, relative to the project directory. Missing directories are created
--name <Class>ApiClientClient class name; the factory is create<Class>
--forceReplace an output file that was not generated by axil

axil g client is the short form. --from, --out and --name are only accepted with client; a positional argument after client is an error.

Overwrite guard

A file at --out is replaced without asking when it was written by axil generate client: it starts with the generated header shown below. Any other existing file is left alone and the command exits with code 1:

Output
TXT
  ■  src/api-client.ts exists and was not generated by axil. Pass --force to overwrite it, or choose another file with --out.
  └

Errors

The command exits with code 1 and a message when the document cannot be used:

SituationMessage
The URL cannot be reachedCould not fetch <url>: … Is the app running? Pass --from <url|file> to use another document.
No answer within 10 secondsTimed out after 10s fetching <url>
Non-2xx answerGET <url> answered <status> <statusText>
The file does not existOpenAPI document not found: <path>
YAML instead of JSON<from> looks like YAML; only JSON documents are supported. Convert it to JSON first.
Swagger 2.0Swagger 2.0 documents are not supported; use OpenAPI 3.x.
Not OpenAPI 3.xNot an OpenAPI 3.x document (openapi: …).
Invalid --nameInvalid client name "…": use a TypeScript identifier such as ApiClient.

Output

For a document with three operations:

Output
TXT
  ┌  axil generate  client
  │
  │    Source  http://localhost:3000/openapi.json
  │    Output  src/api-client.ts
  │
  ○  Reading http://localhost:3000/openapi.json
  ◇  OpenAPI document loaded  Users API, OpenAPI 3.1.0
  ◇  Wrote src/api-client.ts  3 operations, 3 schemas
  │
  ◆  Use it:
  │    import { createApiClient, ApiError } from './api-client.js'
  │    const api = createApiClient({ baseUrl: 'http://localhost:3000', token })
  │
  ◆  Client generated in 24ms
  └

On an interactive terminal the ○ Reading line is a spinner that is replaced by the result. The import path in the hint is relative to src/.

Problems that do not stop generation, such as an external $ref or a skipped cookie parameter, are printed as warnings before the Wrote line.

The generated file

The file has four parts, in this order.

1. Header. It marks the file as generated and is what the overwrite guard looks for:

TypeScript
TS
1/* eslint-disable */
2// Generated by axil generate client. Do not edit: regenerate instead.
3// Source: http://localhost:3000/openapi.json
4// API: Users API v1.0.0 (OpenAPI 3.1.0)
5// Generated at: 2026-11-18T09:00:00.000Z

2. Schemas. One exported type per components.schemas entry. Plain objects become interfaces; descriptions become JSDoc:

TypeScript
TS
1/** Standard AxilJS response envelope (res.success / res.created / …). */
2export interface Envelope {
3  /** HTTP status code */
4  status: number;
5  /** Status name, e.g. 'HTTP_200_OK' */
6  code: string;
7  message: string;
8  /** Response payload (handler-specific, not described). */
9  data: unknown;
10}
11
12export interface PostApiUsersBody {
13  name: string;
14  email: string;
15  role?: "admin" | "user";
16}

3. Operation types. Per operation, as needed: <Operation>Params, <Operation>Query, <Operation>Headers, <Operation>Body, <Operation>Response and <Operation>Input. A name that is already taken gets a numeric suffix (PostApiUsersBody2).

TypeScript
TS
1export interface GetApiUsersByIdParams {
2  id: number;
3}
4
5export type GetApiUsersByIdResponse = Envelope;
6
7export interface GetApiUsersByIdInput {
8  params: GetApiUsersByIdParams;
9}

4. Runtime and client. ApiError, the client class with one method per operation, and the create<Class>() factory:

TypeScript
TS
1export class ApiClient {
2  /** GET /api/users/{id} */
3  getApiUsersById(input: GetApiUsersByIdInput, options?: RequestOptions): Promise<GetApiUsersByIdResponse>
4
5  /**
6   * POST /api/users
7   * Requires a bearer token.
8   */
9  postApiUsers(input: PostApiUsersInput, options?: RequestOptions): Promise<PostApiUsersResponse>
10}
11
12export function createApiClient(options: ApiClientOptions = {}): ApiClient

Methods

  • Method names come from the operationId in camelCase. Without one, the name is derived from the method and path (GET /users/{id} becomes getUsersById). Names that clash with each other or with the client's own members get a suffix, and a warning is printed.
  • Each method takes one input object with params, query, headers and body as the operation needs, then optional RequestOptions (signal, headers). When nothing in input is required, it defaults to {}.
  • Each method returns Promise<<Operation>Response>: the parsed body of the documented 2xx response (the lowest 2xx code, else 2XX, else default). For an AxilJS API this is the { status, code, message, data } envelope. An operation without a response body returns void.
  • Path parameters are URL-encoded. Query values that are arrays are repeated (?tag=a&tag=b), objects are sent as JSON, and undefined or null values are left out.
  • JSON bodies are serialized with JSON.stringify and sent with their documented content-type; application/x-www-form-urlencoded bodies are form-encoded.

Client options

OptionDefaultDescription
baseUrlThe first servers URL of the documentBase URL of the API, without a trailing slash. A server URL with variables is not used as default; pass baseUrl explicitly
tokennoneA bearer token, or a (possibly async) function returning one. Sent as Authorization: Bearer <token> on operations that declare security
fetchglobalThis.fetchfetch implementation. The constructor throws when there is none
headersnoneHeaders sent with every request

ApiError

Every non-2xx response throws an ApiError with status, code, message and the parsed body. code and message are read from an AxilJS error body { error: { code, message } } or from an envelope { code, message }. Otherwise code is HTTP_<status> and message is the status text.

Usage

TypeScript
TS
1import { createApiClient, ApiError } from './api-client.js'
2
3const api = createApiClient({
4  baseUrl: 'https://api.example.com',
5  token: () => session.token          // read on every request that needs it
6})
7
8const { data } = await api.getApiUsers({ query: { page: 2 } })
9
10try {
11  await api.postApiUsers({ body: { name: 'Ann', email: 'ann@example.com' } })
12} catch (error) {
13  if (error instanceof ApiError && error.status === 422) {
14    console.error(error.code, error.message, error.body)
15  } else {
16    throw error
17  }
18}

The file compiles under tsc --strict and needs neither DOM nor Node typings (ES2017 or later lib). At run time it needs a global fetch, or a fetch implementation passed in the options.

Regenerating and CI

Types and methods are sorted by name, so regenerating from the same document produces the same file apart from the timestamp, and a diff shows only real API changes. A CI job can start the API, regenerate the client and fail when the committed client is out of date:

YAML
YAML
1- run: npm ci
2- run: npm run build
3- run: node dist/main.js &
4- run: curl --retry 10 --retry-connrefused --retry-delay 1 -sf http://localhost:3000/openapi.json > /dev/null
5- run: npx axil generate client --out src/api-client.ts
6- run: git diff --exit-code -I '^// Generated at:' -- src/api-client.ts

git diff -I ignores the timestamp line, so the step fails only when the API changed and the committed client was not regenerated.

Alternatively, commit the document (openapi.json) and generate from the file with --from ./openapi.json, which needs no running server.

Limitations

  • Only JSON documents are read. Convert a YAML document to JSON first.
  • Swagger 2.0 documents are not supported.
  • External $refs (to other files or URLs) are not resolved; they are typed as unknown with a warning.
  • Cookie parameters are skipped with a warning.
  • Multipart uploads are not supported. Bodies that are neither JSON nor form-encoded are sent as strings.
  • For an AxilJS API, data in the envelope is unknown, because the generated document does not describe handler output.

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY