Skip to content
Ky logo

Ky

OfficialBetav0.1.0

@kubb/plugin-ky

kubb add plugin-ky

Call operations

Call a generated function with grouped request options, read the typed result, and pass content types or Ky options for one call.

Call an operation

Pass each request part under its own key: path, query, headers, cookies, or body. A key exists only when the operation declares that part:

import { getPetById } from './gen/clients/getPetById'
import { updatePet } from './gen/clients/updatePet'

const { data } = await getPetById({ path: { petId: 1 } })
//      ^ the parsed pet, typed from the 200 response

await updatePet({ path: { petId: 1 }, headers: { 'X-Request-ID': 'r-1' }, body: { name: 'Rex', status: 'sold' } })

await getStatus() // no required parameters, no argument

Path keys keep the spec's names, so {pet-id} takes path: { 'pet-id': 1 }. Set pathParamsCasing: 'camelcase' on the adapter (@kubb/adapter-oas 5.20.0 or later) to pass petId instead.

The examples set integerType: 'number'. With the default bigint, an int64 id takes 1n.

Read the result

A call resolves to a RequestResult, a union narrowed by the numeric status:

type RequestResult = {
  status: number
  data: TData // the parsed success body, undefined on an error result
  error: TError // the parsed error body, undefined on a success result
  contentType: string | undefined // the response media type, without parameters
  headers: Headers // the response headers
  request: Request // rebuilt from the resolved request
  response: Response // the native response
}

With the default throwOnError: true, a resolved call is always a success. Narrow on status when an operation has several success statuses:

const result = await getPetById({ path: { petId: 1 } })

console.info(result.headers.get('x-ratelimit-remaining')) // suggests the declared header names
if (result.status === 200) console.info(result.data)

Unwrap the success body

Call .unwrap() to get only the success body:

const pet = await getPetById({ path: { petId: 1 } }).unwrap()
//    ^ the parsed pet
throwOnErrorA non-2xx response makes .unwrap()
true (default)throw a ResponseError, as a plain await does.
falsereject with the parsed error body.

To get the body from every call, set returnType: 'data' on the plugin.

Set the content type

When an operation accepts or returns several content types, set contentType on the call. A string sets Content-Type, and response sets Accept:

await uploadAvatar({ path: { petId: 1 }, body: avatarBlob, contentType: 'image/png' })

Pass Ky options

Pass options for Ky options such as retry, timeout, and hooks, or fetch settings such as cache and redirect:

await getPetById({ path: { petId: 1 }, options: { timeout: 5000, retry: { limit: 3 } } })

client.setConfig({ options }) sets shared defaults, and per-call options win. Kubb sets the method, headers, body, and signal over them, and sets throwHttpErrors: false to keep control of status handling. options does not take json, prefix, or searchParams, because Kubb builds the body and the URL: pass body, baseURL, and query on the call.

The client sets retry: 0, so a call is sent once, where Ky's own default is 2. See Retry a call to turn it on. Ky's timeout default stays: 10 seconds to get the response headers, or false to wait without a limit.

Build a URL without sending

client.getUrl builds the URL a request would use, with the same base URL and serialization:

import { client } from './gen/.kubb/client'

const url = client.getUrl({ url: '/pets/{petId}', path: { petId: 1 }, query: { fields: 'name' } })
// https://petstore.swagger.io/v2/pets/1?fields=name

Next, handle errors, including throwOnError: false.

Less common cases

Path parameter casing

When you set pathParamsCasing: 'camelcase', the HTTP request stays the same, because path parameter names never reach the wire. The exception is the matrix style, which sends the name (;group-id=42), so an operation with a matrix path parameter keeps its spec names.

Retry a call

Set Ky's retry option to retry a network error, for every call or for one. Ky retries only the methods in retry.methods, which leaves out POST and PATCH:

import { client } from './gen/.kubb/client'

client.setConfig({ options: { retry: { limit: 2 } } })

retry alone does not retry an error status such as 503, because Kubb reads the error response itself, and Ky only retries a status it throws on. To retry a status, return ky.retry() from an afterResponse hook, and stop at the limit so the call gets the last response:

import ky from 'ky'
import { client } from './gen/.kubb/client'

client.setConfig({
  options: {
    retry: { limit: 2 },
    hooks: {
      afterResponse: [({ response, retryCount, options }) => (response.status === 503 && retryCount < options.retry.limit ? ky.retry() : undefined)],
    },
  },
})
ky.retry() skips Ky's retry.methods check, so this hook also resends a POST. Check request.method in the hook when that is not safe.

TRACE operations

When the spec has a trace operation, Kubb generates a call for it, but Ky rejects the TRACE method. Use @kubb/plugin-axios or a custom transport for it.