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.
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.
Options
| Option | Default | Description |
|---|---|---|
--from <url|file> | http://localhost:<PORT>/openapi.json, with PORT from .env, else 3000 | An http(s) URL, fetched with a 10 second timeout, or a local JSON file |
--out <file> | src/api-client.ts | Output file, relative to the project directory. Missing directories are created |
--name <Class> | ApiClient | Client class name; the factory is create<Class> |
--force | Replace 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:
■ 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:
| Situation | Message |
|---|---|
| The URL cannot be reached | Could not fetch <url>: … Is the app running? Pass --from <url|file> to use another document. |
| No answer within 10 seconds | Timed out after 10s fetching <url> |
| Non-2xx answer | GET <url> answered <status> <statusText> |
| The file does not exist | OpenAPI document not found: <path> |
| YAML instead of JSON | <from> looks like YAML; only JSON documents are supported. Convert it to JSON first. |
| Swagger 2.0 | Swagger 2.0 documents are not supported; use OpenAPI 3.x. |
| Not OpenAPI 3.x | Not an OpenAPI 3.x document (openapi: …). |
Invalid --name | Invalid client name "…": use a TypeScript identifier such as ApiClient. |
Output
For a document with three operations:
┌ 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:
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.000Z2. Schemas. One exported type per components.schemas entry. Plain objects become interfaces; descriptions become JSDoc:
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).
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:
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 = {}): ApiClientMethods
- Method names come from the
operationIdin camelCase. Without one, the name is derived from the method and path (GET /users/{id}becomesgetUsersById). 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
inputobject withparams,query,headersandbodyas the operation needs, then optionalRequestOptions(signal,headers). When nothing ininputis required, it defaults to{}. - Each method returns
Promise<<Operation>Response>: the parsed body of the documented 2xx response (the lowest 2xx code, else2XX, elsedefault). For an AxilJS API this is the{ status, code, message, data }envelope. An operation without a response body returnsvoid. - Path parameters are URL-encoded. Query values that are arrays are repeated (
?tag=a&tag=b), objects are sent as JSON, andundefinedornullvalues are left out. - JSON bodies are serialized with
JSON.stringifyand sent with their documentedcontent-type;application/x-www-form-urlencodedbodies are form-encoded.
Client options
| Option | Default | Description |
|---|---|---|
baseUrl | The first servers URL of the document | Base URL of the API, without a trailing slash. A server URL with variables is not used as default; pass baseUrl explicitly |
token | none | A bearer token, or a (possibly async) function returning one. Sent as Authorization: Bearer <token> on operations that declare security |
fetch | globalThis.fetch | fetch implementation. The constructor throws when there is none |
headers | none | Headers 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
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:
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.tsgit 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 asunknownwith 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,
datain the envelope isunknown, because the generated document does not describe handler output.
Related
- OpenAPI: the document
app.serveOpenAPI()serves - JSON Schema: how
validate()schemas become request types - Project commands: the other
axil generatekinds
Was this page helpful?