@kubb/plugin-axios 6.0.2 → 6.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,28 +1,41 @@
1
1
  # Use a custom transport
2
2
 
3
- Set a transport at runtime to replace the network send. The client still builds URLs, serializes parameters, resolves authentication, and handles results.
3
+ Replace the network send of the generated axios client with your own axios instance or function.
4
4
 
5
- The transport is a function that takes the resolved request and returns a web `Response` with the native axios config and response, as in `@kubb/plugin-fetch`. The default is `defaultTransport`, which sends through `getAxiosInstance()`. `createAxiosTransport(instance)` turns any axios instance into a transport.
5
+ The client still builds the URL, serializes parameters, resolves auth, runs interceptors, and decodes the result. `client.interceptors` handlers keep running, whatever the transport.
6
+
7
+ ## Write a transport function
8
+
9
+ A transport gets the resolved request and returns a web `Response` with its body unread:
6
10
 
7
11
  ```typescript
8
- type ClientConfig = {
9
- // ...
10
- transport?: Transport
12
+ type Transport = (request: ResolvedRequest) => Promise<Response | TransportResult>
13
+
14
+ type ResolvedRequest = {
15
+ url: string // built, with the query
16
+ method: string
17
+ headers: Record<string, string> // auth headers included
18
+ body?: RequestBody // already encoded
19
+ signal?: AbortSignal
20
+ credentials?: RequestCredentials
21
+ options?: NativeOptions // AxiosRequestConfig
22
+ stream?: boolean // the call streams the response, so do not buffer the body
11
23
  }
24
+
25
+ type TransportResult = { webResponse: Response; request: AxiosRequestConfig; response: AxiosResponse }
12
26
  ```
13
27
 
14
- ## Send through a pre-configured instance
28
+ Return a `TransportResult` to set the native `request` and `response` that results and errors carry. See [Results from a plain `Response`](#results-from-a-plain-response).
29
+
30
+ ## Send through your own axios instance
15
31
 
16
- Wrap an instance with a timeout, default headers, and a logging interceptor:
32
+ `createAxiosTransport(instance)` turns any axios instance into a transport, with its defaults, adapter, and interceptors:
17
33
 
18
34
  ```typescript
19
35
  import axios from 'axios'
20
36
  import { client, createAxiosTransport } from './gen/.kubb/client'
21
37
 
22
- const instance = axios.create({
23
- timeout: 10_000,
24
- headers: { 'X-Client': 'kubb' },
25
- })
38
+ const instance = axios.create({ timeout: 10_000, headers: { 'X-Client': 'kubb' } })
26
39
 
27
40
  instance.interceptors.response.use((response) => {
28
41
  console.info(`${response.config.method?.toUpperCase()} ${response.config.url} -> ${response.status}`)
@@ -32,39 +45,49 @@ instance.interceptors.response.use((response) => {
32
45
  client.setConfig({ transport: createAxiosTransport(instance) })
33
46
  ```
34
47
 
35
- Every generated function now sends through your instance, so its timeout, headers, and axios interceptors apply to each call. Handlers registered through `client.interceptors` keep running, whatever the transport.
36
-
37
48
  > [!NOTE]
38
- > Kubb sets `url`, `method`, `headers`, `data`, `transformRequest`, `transformResponse`, `responseType`, and `validateStatus` for its own serialization and status handling, so leave those fields alone. Set timeouts, retries, and interceptors on the instance. For one call, pass `options`, such as `{ timeout }` or `{ onUploadProgress }`, instead of building a new instance.
49
+ > Kubb sets `url`, `method`, `headers`, `data`, `transformRequest`, `transformResponse`, `responseType`, and `validateStatus`, so leave those alone. For one call, pass `options`, such as `{ timeout }`, instead of a new instance.
39
50
 
40
- ## Configure the default instance
51
+ ## Wrap the default transport
41
52
 
42
- The generated client exports `getAxiosInstance()`, which returns the instance `defaultTransport` sends through. Configure it directly to add tracing or headers without replacing the transport:
53
+ `defaultTransport` sends through the instance `getAxiosInstance()` returns. Configure that instance, or wrap the transport to add tracing or timing:
43
54
 
44
55
  ```typescript
45
- import { getAxiosInstance } from './gen/.kubb/client'
56
+ import { client, defaultTransport, getAxiosInstance } from './gen/.kubb/client'
46
57
 
47
58
  getAxiosInstance().defaults.timeout = 10_000
48
- getAxiosInstance().interceptors.request.use((config) => {
49
- config.headers.set('traceparent', currentTraceparent())
50
- return config
59
+
60
+ client.setConfig({
61
+ transport: (request) => withSpan(request, () => defaultTransport(request)),
51
62
  })
52
63
  ```
53
64
 
54
- An instance from `createClient()` copies the `transport` of `client` when you create it, unless you pass its own. A later `client.setConfig({ transport })` does not reach it. Without a `transport` on either, it sends through `getAxiosInstance()`.
65
+ ## Mock the network in tests
66
+
67
+ Return a fixed `Response` from a separate client, and pass it to the call or to a query plugin:
68
+
69
+ ```typescript
70
+ import { createClient } from './gen/.kubb/client'
71
+ import { getPetById } from './gen/clients/getPetById'
72
+
73
+ const testClient = createClient({ transport: async () => Response.json({ id: 1, name: 'Fluffy' }) })
74
+
75
+ const { data } = await getPetById({ path: { petId: 1 }, client: testClient })
76
+ // ^ { id: 1, name: 'Fluffy' }
77
+ ```
55
78
 
56
79
  ## Where to set it
57
80
 
58
- Use `client.setConfig({ transport })` for shared configuration, `createClient({ transport })` for an isolated instance, or pass `transport` on an operation to override it for one call.
81
+ | Scope | How |
82
+ | ----------------- | --------------------------------- |
83
+ | Every call | `client.setConfig({ transport })` |
84
+ | A separate client | `createClient({ transport })` |
85
+ | One call | `transport` on the call |
59
86
 
60
- ## Write a transport function
87
+ A client from `createClient()` copies the shared `transport` at creation, so a later `client.setConfig({ transport })` does not reach it. Without a `transport`, it sends through `getAxiosInstance()`.
61
88
 
62
- A custom function can wrap `defaultTransport`, or the transport of any instance:
89
+ ## Less common cases
63
90
 
64
- ```typescript
65
- import { client, defaultTransport } from './gen/.kubb/client'
91
+ ### Results from a plain `Response`
66
92
 
67
- client.setConfig({
68
- transport: (request) => withSpan(request, () => defaultTransport(request)),
69
- })
70
- ```
93
+ When a transport returns a plain `Response`, results and errors carry it as `response`. Their `request` is a `Request` built from the resolved request without its body, or the resolved request itself when `Request` cannot parse the URL, such as a relative URL in Node.js. Return a `TransportResult` to set both, as [Write a transport function](#write-a-transport-function) shows.
package/docs/options.md CHANGED
@@ -4,35 +4,46 @@ Pass these options to `pluginAxios()`. Shared options link to [Shared plugin opt
4
4
 
5
5
  ## Options overview
6
6
 
7
- | Option | Purpose | Default |
8
- | ------------------------------------------------------------------------- | ---------------------------------------------------------------------- | ------------------------------------------------ |
9
- | [`output`](https://kubb.dev/docs/5.x/reference/plugin-options#output) | Where files are written: `path`, `mode`, `barrel`, `banner`, `footer`. | `{ path: 'clients', barrel: { type: 'named' } }` |
10
- | [`group`](https://kubb.dev/docs/5.x/reference/plugin-options#group) | Split output by tag or path: `type`, `name`. | None |
11
- | [`baseURL`](#baseurl) | Base URL prepended to every request. | None |
12
- | [`throwOnErrorDefault`](#throwonerrordefault) | Default error behavior and return type for generated operations. | `true` |
13
- | [`validator`](#validator) | Validate request bodies, params, and responses with Zod. | `false` |
14
- | [`sdk`](#sdk) | Emit a class-based SDK instead of standalone functions. | None |
15
- | [`returnType`](#returntype) | Shape of the value a generated call resolves to. | `'full'` |
16
- | [`include`](https://kubb.dev/docs/5.x/reference/plugin-options#include) | Keep only operations that match. | None |
17
- | [`exclude`](https://kubb.dev/docs/5.x/reference/plugin-options#exclude) | Skip operations that match. | `[]` |
18
- | [`override`](https://kubb.dev/docs/5.x/reference/plugin-options#override) | Apply different options per pattern. | `[]` |
19
- | [`resolver`](#resolver) | Customize generated names and file paths. | `resolverClient` |
20
- | [`macros`](https://kubb.dev/docs/5.x/reference/plugin-options#macros) | Rewrite AST nodes before printing. | `[]`, run after the built-in client macros |
7
+ | Option | Purpose | Default |
8
+ | ------------------------------------------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------ |
9
+ | [`output`](https://kubb.dev/docs/5.x/reference/plugin-options#output) | Where files are written. | `{ path: 'clients', barrel: { type: 'named' } }` |
10
+ | [`group`](https://kubb.dev/docs/5.x/reference/plugin-options#group) | Split output by tag or path. | None |
11
+ | [`baseURL`](#baseurl) | Base URL the client starts with. | None |
12
+ | [`throwOnErrorDefault`](#throwonerrordefault) | Throw on a non-2xx response unless a call says otherwise. | `true` |
13
+ | [`validator`](#validator) | Validate requests and responses with Zod. | `false` |
14
+ | [`returnType`](#returntype) | What a call resolves to. | `'full'` |
15
+ | [`sdk`](#sdk) | Generate classes instead of standalone functions. | None |
16
+ | [`sdk.mode`](#sdk) | One class per tag, or one class with every operation. | `'tag'` |
17
+ | [`sdk.name`](#sdk) | Name and file of the root or flat class. | None, or `'sdk'` with `mode: 'flat'` |
18
+ | [`include`](https://kubb.dev/docs/5.x/reference/plugin-options#include) | Keep only operations that match. | None |
19
+ | [`exclude`](https://kubb.dev/docs/5.x/reference/plugin-options#exclude) | Skip operations that match. | `[]` |
20
+ | [`override`](https://kubb.dev/docs/5.x/reference/plugin-options#override) | Options per pattern, except `throwOnErrorDefault`. | `[]` |
21
+ | [`resolver`](https://kubb.dev/docs/5.x/reference/plugin-options#resolver) | Generated names and paths, plus the [SDK names](#resolver). | `resolverClient` |
22
+ | [`macros`](https://kubb.dev/docs/5.x/reference/plugin-options#macros) | Rewrite AST nodes before printing. | `[]`, run after the built-in client macros |
21
23
 
22
24
  ## Option details
23
25
 
24
26
  ### baseURL
25
27
 
26
- Base URL prepended to every request. When omitted, each request uses the operation's relative path from the spec, with no fallback to the top-level server URL. A path or operation that declares its own `servers` uses that URL instead. See [Set the base URL](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/base-url). A value with a `${...}` interpolation is emitted as a template literal, so `baseURL: '${process.env.API_URL}'` reads the environment variable at runtime.
28
+ The base URL the client starts with. `client.setConfig({ baseURL })` replaces it at runtime.
27
29
 
28
30
  | | |
29
31
  | -------- | -------- |
30
32
  | Type | `string` |
31
33
  | Required | `false` |
32
34
 
35
+ A `${...}` interpolation becomes a template literal, so it reads the environment at runtime:
36
+
37
+ ```typescript
38
+ pluginAxios({ baseURL: '${process.env.API_URL}' })
39
+ ```
40
+
41
+ > [!NOTE]
42
+ > The spec's top-level `servers` URL is never used. See [Set the base URL](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/configure-requests#set-the-base-url).
43
+
33
44
  ### throwOnErrorDefault
34
45
 
35
- Set `throwOnErrorDefault: false` to return documented error responses as values by default. The option sets the fallback on each generated request and the default `ThrowOnError` type parameter on functions and SDK methods. The option applies to the whole plugin, so `override` cannot set it. A call that passes `throwOnError` still wins. With `throwOnError: true`, a non-2xx response throws and the return type narrows to successful responses. Query hooks always pass `throwOnError: true`.
46
+ The `throwOnError` a generated function or SDK method uses when the call leaves it out. Neither `override` nor `client.setConfig({ throwOnError })` changes it. Query hooks always pass `throwOnError: true`.
36
47
 
37
48
  | | |
38
49
  | -------- | --------- |
@@ -43,14 +54,12 @@ Set `throwOnErrorDefault: false` to return documented error responses as values
43
54
  ```typescript
44
55
  // with pluginAxios({ throwOnErrorDefault: false })
45
56
  const result = await getPetById({ path: { petId: 1 } })
46
- if (result.status !== 200) console.error(result.status, result.error)
57
+ if (result.error !== undefined) console.error(result.status, result.error)
47
58
  ```
48
59
 
49
- The examples set [`integerType: 'number'`](https://kubb.dev/extensions/kubb-labs/adapter-oas/options#integertype) on the adapter, so an `int64` id such as `petId` is a `number`. With the default it is a `bigint` and the call takes `1n`.
50
-
51
60
  ### validator
52
61
 
53
- Validates request bodies, the path, query, header, and cookie params, and response bodies with schemas from `@kubb/plugin-zod`, so add `pluginZod()` too. An invalid value makes the generated function throw a `ParseError`.
62
+ Checks requests and responses against the schemas of `@kubb/plugin-zod`, so add `pluginZod()` too. A value that fails its schema throws a `ParseError`.
54
63
 
55
64
  | | |
56
65
  | -------- | ------------------------------------------------------------------------- |
@@ -61,15 +70,15 @@ Validates request bodies, the path, query, header, and cookie params, and respon
61
70
  ::field-group
62
71
 
63
72
  :::field{name="false"}
64
- Default value. Skips validation and casts the response to the generated type.
73
+ Default value. No validation. The response is cast to the generated type.
65
74
  :::
66
75
 
67
76
  :::field{name="'zod'"}
68
- Validates the success response body, and the error body against the schema of its status.
77
+ Validates the success body, and an error body against the schema of its status.
69
78
  :::
70
79
 
71
80
  :::field{name="{ request?: 'zod', params?: 'zod', response?: 'zod' }"}
72
- Enables validation separately for request bodies, params, and responses.
81
+ Opts in per part. `request` checks the body and `params` the path, query, header, and cookie params before the send. `response` works as `'zod'`.
73
82
  :::
74
83
 
75
84
  ::
@@ -83,109 +92,87 @@ import { pluginAxios } from '@kubb/plugin-axios'
83
92
  export default defineConfig({
84
93
  input: './petStore.yaml',
85
94
  output: { path: './src/gen' },
86
- plugins: [
87
- pluginTs(),
88
- pluginZod(),
89
- pluginAxios({ validator: { request: 'zod', params: 'zod', response: 'zod' } }),
90
- ],
95
+ plugins: [pluginTs(), pluginZod(), pluginAxios({ validator: { request: 'zod', params: 'zod', response: 'zod' } })],
91
96
  })
92
97
  ```
93
98
 
94
- `params` runs each group through its generated `<operation>PathSchema`, `QuerySchema`, `HeadersSchema`, or `CookiesSchema`, and sends what the schema returns. A codec param such as a `Date` goes out in its wire form, and an invalid param fails before the request. Values added by `auth` are not validated.
95
-
96
- Only the params your OpenAPI spec declares are sent. Path and query keys the spec does not declare are stripped, so a key such as an undocumented filter or a cache-buster never reaches the URL. Declare it in the spec, or leave `params` off. Headers are the exception. Client-level `headers`, such as `Authorization` or tracing headers, are merged with the call's headers before validation. Headers the spec does not declare pass through unchanged, and declared header params match in any casing.
99
+ See [Turn validation off at runtime](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/error-handling#turn-validation-off-at-runtime) and [Parameter validation](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/serialization#parameter-validation).
97
100
 
98
- Pair `request` and `params` with `pluginZod({ inferred: 'codec' })` when the schemas use codecs, so the request types accept the domain values (such as a `Date`) that the validators encode. See [`inferred`](https://kubb.dev/extensions/kubb-labs/plugin-zod/options#inferred).
99
-
100
- ### sdk
101
+ ### returnType
101
102
 
102
- Generates a class-based SDK. Each instance takes its own client config, so environments can use separate clients. Leave `sdk` unset to keep the standalone functions that query plugins call.
103
+ What a generated function or SDK method resolves to. The query plugins and `@kubb/plugin-mcp` read it too.
103
104
 
104
- | | |
105
- | -------- | ------------------------------------------- |
106
- | Type | `{ mode?: 'tag' \| 'flat'; name?: string }` |
107
- | Required | `false` |
105
+ | | |
106
+ | -------- | ------------------ |
107
+ | Type | `'full' \| 'data'` |
108
+ | Required | `false` |
109
+ | Default | `'full'` |
108
110
 
109
111
  ::field-group
110
112
 
111
- :::field{name="'tag'"}
112
- Default value for `sdk.mode`. Generates one class per tag, such as `PetClient`. Set `sdk.name` to also get a root class that shares one client with every tag, used as `new PetStore(config).pet.getPetById(...)`.
113
+ :::field{name="'full'"}
114
+ Default value. The full result: `{ status, data, error, contentType, headers, request, response }`.
113
115
  :::
114
116
 
115
- :::field{name="'flat'"}
116
- Generates one class named by `sdk.name`, with every operation as a method. Supports single-file output.
117
+ :::field{name="'data'"}
118
+ The success body. With `throwOnError: false`, the full result, so the caller can tell an error from a success.
117
119
  :::
118
120
 
119
121
  ::
120
122
 
121
- `mode: 'tag'` needs one file per tag, so it throws [`KUBB_INVALID_PLUGIN_OPTIONS`](https://kubb.dev/docs/5.x/reference/diagnostics#kubb-invalid-plugin-options) with single-file output. Use `mode: 'flat'` for a single file.
122
-
123
- Methods take the same grouped options and return the same result as the standalone functions. See [Call operations](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/calling-operations).
124
-
125
123
  ```typescript
126
- const pet = new PetClient({ baseURL: 'https://petstore.swagger.io/v2' })
127
- const { data } = await pet.getPetById({ path: { petId: 1 } })
128
- ```
129
-
130
- Each SDK class exposes its client as the read-only `client` field. Interceptors on the root class's `client` apply to every tag:
124
+ pluginAxios({ returnType: 'data' })
131
125
 
132
- ```typescript
133
- const api = new PetStore({ baseURL: 'https://petstore.swagger.io/v2' })
134
- api.client.interceptors.request.use((request) => request)
135
- await api.pet.getPetById({ path: { petId: 1 } })
126
+ const pet = await getPetById({ path: { petId: 1 } }) // Pet, not { status, data, ... }
136
127
  ```
137
128
 
138
- A tag class also accepts an existing client, as in `new PetClient(api.client)`.
129
+ See [Read headers with `returnType: 'data'`](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/error-handling#read-headers-with-returntype-data).
139
130
 
140
- ### returnType
131
+ ### sdk
141
132
 
142
- Shape of the value a generated call resolves to.
133
+ Generates classes instead of standalone functions. Each instance builds its own client from its config, so two environments are two instances.
143
134
 
144
- | | |
145
- | -------- | ------------------ |
146
- | Type | `'full' \| 'data'` |
147
- | Required | `false` |
148
- | Default | `'full'` |
135
+ | | |
136
+ | -------- | ------------------------------------------- |
137
+ | Type | `{ mode?: 'tag' \| 'flat'; name?: string }` |
138
+ | Required | `false` |
149
139
 
150
140
  ::field-group
151
141
 
152
- :::field{name="'full'"}
153
- Default value. Returns `{ status, data, error, contentType, headers, request, response }`. `headers` is the response's `Headers`. For an operation whose responses declare `headers`, its `get` suggests those names once `status` is narrowed, and the values stay strings.
142
+ :::field{name="mode: 'tag'"}
143
+ Default value. One class per tag, such as `PetClient`. With `name`, a root class also shares one client with every tag: `new PetStore(config).pet.getPetById(...)`. Throws [`KUBB_INVALID_PLUGIN_OPTIONS`](https://kubb.dev/docs/5.x/reference/diagnostics#kubb-invalid-plugin-options) with single-file output.
154
144
  :::
155
145
 
156
- :::field{name="'data'"}
157
- Returns the success body when `throwOnError` is `true`. With `throwOnError: false`, returns the full result so callers can tell errors from successes.
146
+ :::field{name="mode: 'flat'"}
147
+ One class named by `name`, with every operation as a method. Without `name`, the class is `Sdk` in `sdk.ts`. Works with single-file output.
158
148
  :::
159
149
 
160
150
  ::
161
151
 
152
+ Methods take the same options and return the same result as the standalone functions. Interceptors on the root class's `client` reach every tag:
153
+
162
154
  ```typescript
163
- pluginAxios({ returnType: 'data' })
155
+ const api = new PetStore({ baseURL: 'https://petstore.swagger.io/v2' })
156
+ api.client.interceptors.request.use((request) => request)
157
+ await api.pet.getPetById({ path: { petId: 1 } })
164
158
 
165
- const pet = await getPetById({ path: { petId: 1 } }) // Pet, not { status, data, ... }
159
+ const pets = new PetClient(api.client) // a tag class also accepts an existing client
166
160
  ```
167
161
 
168
- `returnType` applies to the functions and the SDK. The query plugins and `@kubb/plugin-mcp` read it too, including a per-operation value set through [`override`](https://kubb.dev/docs/5.x/reference/plugin-options#override). To read headers such as `ETag` under `'data'`, pass `throwOnError: false` and read `result.response.headers`.
162
+ > [!WARNING]
163
+ > The query plugins and `@kubb/plugin-mcp` call the standalone functions, so leave `sdk` unset for them.
169
164
 
170
165
  ### resolver
171
166
 
172
- Overrides generated file and symbol names. Omitted members keep `resolverClient`. The shared members (`name`, `file`, `imports`) and the `this` context are described under [`resolver`](https://kubb.dev/docs/5.x/reference/plugin-options#resolver).
167
+ Adds three members to the shared [`resolver`](https://kubb.dev/docs/5.x/reference/plugin-options#resolver). Members you leave out keep `resolverClient`.
173
168
 
174
169
  | | |
175
170
  | -------- | ------------------------------- |
176
171
  | Type | `ResolverPatch<ResolverClient>` |
177
172
  | Required | `false` |
178
173
 
179
- ```typescript [Partial override]
180
- type ResolverClientPatch = {
181
- name?(name: string): string
182
- file?: {
183
- baseName?(params: { name: string; extname: string }): string
184
- path?(params: { baseName: string; output: Output }): string
185
- }
186
- imports?(options: ResolveImportsOptions): Array<ImportNode>
187
- className?(name: string): string
188
- groupName?(name: string): string // → 'PetClient'
189
- propertyName?(name: string): string
190
- }
191
- ```
174
+ | Member | Names | Example |
175
+ | -------------------- | --------------------------------------------------------------------- | ------------------------------------ |
176
+ | `className(name)` | The root class, the flat class, and the class of untagged operations. | `className('petStore')` → `PetStore` |
177
+ | `groupName(name)` | A tag class. | `groupName('pet')` → `PetClient` |
178
+ | `propertyName(name)` | The field a tag class has on the root class. | `propertyName('pet')` → `pet` |
package/docs/overview.md CHANGED
@@ -1,28 +1,30 @@
1
1
  # Axios
2
2
 
3
- The Axios plugin turns each operation in your OpenAPI spec into a typed async function that sends the request with axios. Each function takes grouped `path`, `query`, `headers`, and `body` parameters and returns a result keyed by status code.
3
+ Generates one typed async function per OpenAPI operation that sends the request with axios and returns a result keyed by status code.
4
4
 
5
- The query plugins (`@kubb/plugin-react-query`, `@kubb/plugin-vue-query`, and `@kubb/plugin-swr`) and `@kubb/plugin-mcp` call these functions. The plugin also copies its runtime files to `.kubb/` in the root output folder. Import the client from `.kubb/client.ts`.
5
+ Each function takes grouped `path`, `query`, `headers`, `cookies`, and `body` options. The query plugins and `@kubb/plugin-mcp` call these functions. The runtime is copied into `.kubb/`, so the generated code imports only `axios`.
6
6
 
7
7
  ## Setup
8
8
 
9
9
  - Add `@kubb/plugin-ts` for the operation types, or `@kubb/plugin-zod` with `inferred: true`.
10
- - Add `@kubb/plugin-zod` when you set `validator`, and install `zod` v4. Generation fails without the plugin.
11
- - Install `axios` 1.20 or a later v1 release in the app that uses the generated code.
10
+ - Add `@kubb/plugin-zod` and install `zod` v4 when you set `validator`. Generation fails without the plugin.
11
+ - Install `axios` 1.20 or a later 1.x release in the app that runs the generated code.
12
12
 
13
13
  ## Options worth knowing
14
14
 
15
- - `baseURL` is prepended to every request. The spec's top-level `servers` URL is not used, so without `baseURL` you set one at runtime with `client.setConfig({ baseURL })`. Operations with their own `servers`, on the path or the operation, call that URL instead.
16
- - `validator: 'zod'` validates response bodies with the schemas from `@kubb/plugin-zod`. Use `{ request: 'zod', response: 'zod' }` to also validate request bodies.
17
- - `throwOnErrorDefault: false` returns non-2xx responses as values instead of throwing. A single call can still pass `throwOnError`.
18
- - `returnType: 'data'` makes a call resolve to the success body instead of the full result. With `throwOnError: false`, the call still returns the full result.
19
- - `sdk` generates a class-based SDK, grouped by tag or flat, instead of standalone functions. The query plugins and `@kubb/plugin-mcp` need the standalone functions, so leave `sdk` unset when you use them.
15
+ | Option | Set it to |
16
+ | --------------------- | ------------------------------------------------------------------------------------------ |
17
+ | `baseURL` | The starting host. The spec's top-level `servers` URL is not used. |
18
+ | `validator` | `'zod'` to check response bodies, or `{ request, params, response }` per part. |
19
+ | `throwOnErrorDefault` | `false` to return non-2xx responses as values. |
20
+ | `returnType` | `'data'` to resolve to the success body instead of the full result. |
21
+ | `sdk` | Classes instead of functions. Leave it unset for the query plugins and `@kubb/plugin-mcp`. |
20
22
 
21
- See [Options](https://kubb.dev/extensions/kubb-labs/plugin-axios/options) for every option and its default.
23
+ Next, [call operations](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/calling-operations), or see every option and its default in [Options](https://kubb.dev/extensions/kubb-labs/plugin-axios/options).
22
24
 
23
25
  ## Example
24
26
 
25
- The config below generates an axios client that sends every request to the Petstore API.
27
+ ::code-group
26
28
 
27
29
  ```typescript [kubb.config.ts]
28
30
  import { defineConfig } from 'kubb/config'
@@ -34,9 +36,25 @@ export default defineConfig({
34
36
  input: './petStore.yaml',
35
37
  output: { path: './src/gen' },
36
38
  adapter: adapterOas({ integerType: 'number' }),
37
- plugins: [
38
- pluginTs(),
39
- pluginAxios({ baseURL: 'https://petstore.swagger.io/v2' }),
40
- ],
39
+ plugins: [pluginTs(), pluginAxios({ baseURL: 'https://petstore.swagger.io/v2' })],
41
40
  })
42
41
  ```
42
+
43
+ ```typescript [src/app.ts]
44
+ import { getPetById } from './gen/clients/getPetById'
45
+
46
+ const { data } = await getPetById({ path: { petId: 1 } })
47
+ ```
48
+
49
+ ```text [Generated files]
50
+ src/gen/
51
+ ├── .kubb/ # the runtime: client.ts, core.ts, config.ts, serializers/, ...
52
+ ├── clients/
53
+ │ ├── getPetById.ts
54
+ │ └── index.ts
55
+ └── types/
56
+ ```
57
+
58
+ ::
59
+
60
+ With [`integerType: 'number'`](https://kubb.dev/extensions/kubb-labs/adapter-oas/options#integertype), an `int64` id such as `petId` is a `number`. With the default `bigint`, pass `1n`.
@@ -19,7 +19,7 @@
19
19
  ],
20
20
  "optionalDependencies": ["plugin-ts", "plugin-zod"],
21
21
  "compatibility": {
22
- "kubb": ">=5.18.4",
22
+ "kubb": ">=5.19.0",
23
23
  "node": ">=22.22"
24
24
  },
25
25
  "role": "client",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubb/plugin-axios",
3
- "version": "6.0.2",
3
+ "version": "6.0.4",
4
4
  "description": "Generate a slim, type-safe HTTP client with Kubb based on axios.",
5
5
  "keywords": [
6
6
  "api-client",
@@ -83,8 +83,8 @@
83
83
  "registry": "https://registry.npmjs.org/"
84
84
  },
85
85
  "dependencies": {
86
- "@kubb/kit": "^5.19.0",
87
- "@kubb/plugin-client": "^6.0.2"
86
+ "@kubb/kit": "^5.20.1",
87
+ "@kubb/plugin-client": "^6.0.4"
88
88
  },
89
89
  "devDependencies": {
90
90
  "axios": "^1.21.1",
@@ -1,101 +0,0 @@
1
- # Authenticate requests
2
-
3
- Set an `auth` resolver on the generated client. Operations use the [security schemes](https://spec.openapis.org/oas/v3.1.0#security-scheme-object) declared in your OpenAPI spec. Requests remain unauthenticated until you provide credentials.
4
-
5
- ## Set the auth resolver
6
-
7
- Set the resolver for all secured operations:
8
-
9
- ```typescript
10
- import { client } from './gen/.kubb/client'
11
-
12
- client.setConfig({
13
- auth: () => localStorage.getItem('token') ?? undefined,
14
- })
15
- ```
16
-
17
- `auth` takes a token string or a function. The function can be async and returns a token, or `undefined` to skip that scheme. The runtime sends the first security requirement whose schemes all get a token. A requirement that needs an API key and a session cookie together sends both.
18
-
19
- ## Read the schemes of the spec
20
-
21
- `.kubb/client.ts` exports the schemes of the spec by name as `securitySchemes`. A `mutualTLS` scheme is left out, because its credential is a client certificate in the TLS handshake, not a token the `auth` resolver can return. See [Use mutual TLS](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/authentication#use-mutual-tls). A generated operation points at its schemes there, and adds the scopes it needs:
22
-
23
- ```typescript
24
- security: [{ ...securitySchemes.petstore_auth, scopes: ['write:pets'] }]
25
- ```
26
-
27
- ## Return the right token per scheme
28
-
29
- Use the scheme passed to the resolver to select a credential:
30
-
31
- ```typescript
32
- type Auth = {
33
- type: 'http' | 'apiKey' | 'oauth2' | 'openIdConnect'
34
- scheme?: 'bearer' | 'basic'
35
- name?: string
36
- in?: 'header' | 'query' | 'cookie'
37
- }
38
- ```
39
-
40
- The scheme decides where the runtime puts the token:
41
-
42
- | Scheme in the spec | `Auth` object | Where the token goes |
43
- | ------------------ | ---------------------------------------- | ------------------------------- |
44
- | `http` bearer | `{ type: 'http', scheme: 'bearer' }` | `Authorization: Bearer <token>` |
45
- | `http` basic | `{ type: 'http', scheme: 'basic' }` | `Authorization: Basic <token>` |
46
- | `apiKey` header | `{ type: 'apiKey', name, in: 'header' }` | request header named `name` |
47
- | `apiKey` query | `{ type: 'apiKey', name, in: 'query' }` | query parameter named `name` |
48
- | `apiKey` cookie | `{ type: 'apiKey', name, in: 'cookie' }` | `Cookie` header |
49
- | `oauth2` | `{ type: 'oauth2' }` | `Authorization: Bearer <token>` |
50
- | `openIdConnect` | `{ type: 'openIdConnect' }` | `Authorization: Bearer <token>` |
51
-
52
- > [!NOTE]
53
- > For basic auth, return the raw `username:password` string. The runtime base64-encodes it and writes the `Basic` prefix, so you never build the header yourself.
54
-
55
- When a spec mixes schemes, branch on the `Auth` object and return the matching credential:
56
-
57
- ```typescript
58
- client.setConfig({
59
- auth: (auth) => (auth.type === 'apiKey' ? apiKey : accessToken),
60
- })
61
- ```
62
-
63
- ## Use a separate client per environment
64
-
65
- To give each environment its own token, such as one per tenant in a multi-tenant app, build an isolated client with `createClient`:
66
-
67
- ```typescript
68
- import { createClient } from './gen/.kubb/client'
69
-
70
- const tenant = createClient({
71
- baseURL: 'https://tenant.example.com',
72
- auth: () => tenantToken,
73
- })
74
-
75
- const { data } = await getPetById({ path: { petId: 1 }, client: tenant })
76
- ```
77
-
78
- The examples set [`integerType: 'number'`](https://kubb.dev/extensions/kubb-labs/adapter-oas/options#integertype) on the adapter, so an `int64` id such as `petId` is a `number`. With the default it is a `bigint` and the call takes `1n`.
79
-
80
- To override the client for one request, pass `auth` on that single call, which suits a one-off token refresh. A header you set yourself always wins over the resolved token: client-level `headers`, or `headers` on a call to an operation that declares header parameters.
81
-
82
- For authentication outside OpenAPI security schemes, use an async request interceptor to sign requests or supply custom headers.
83
-
84
- ## Use mutual TLS
85
-
86
- For a `mutualTLS` scheme, give the axios instance the client certificate in Node.js. Every request then presents it:
87
-
88
- ```typescript
89
- import { readFileSync } from 'node:fs'
90
- import { Agent } from 'node:https'
91
- import axios from 'axios'
92
- import { client, createAxiosTransport } from './gen/.kubb/client'
93
-
94
- const instance = axios.create({
95
- httpsAgent: new Agent({ cert: readFileSync('client.crt'), key: readFileSync('client.key') }),
96
- })
97
-
98
- client.setConfig({ transport: createAxiosTransport(instance) })
99
- ```
100
-
101
- In the browser, the browser picks the client certificate itself.