Skip to content

Class-based SDK

Set sdk to emit a class-based client, one class per tag with mode: 'tag' or a single flat class with mode: 'flat'.

kubb.config.ts
typescript
import { defineConfig } from 'kubb/config'
import { pluginTs } from '@kubb/plugin-ts'
import { pluginFetch } from '@kubb/plugin-fetch'

export default defineConfig({
  input: './petStore.yaml',
  output: { path: './src/gen', clean: true },
  plugins: [
    pluginTs(),
    pluginFetch({
      output: { path: 'clients', mode: 'directory' },
      sdk: { mode: 'tag' },
    }),
  ],
})

Output example

src/gen/clients/petClient.ts
typescript
import type { ClientConfig, ClientInstance, Options, RequestResult } from '../.kubb/client'
import type { GetPetByIdOptions, GetPetByIdResponses } from '../types/GetPetById'
import { createClient } from '../.kubb/client'

export class PetClient {
  private readonly client: ClientInstance

  constructor(config: ClientConfig = {}) {
    this.client = createClient(config)
  }

  public getPetById<ThrowOnError extends boolean = true>(options: Options<GetPetByIdOptions, ThrowOnError>): Promise<RequestResult<GetPetByIdResponses, ThrowOnError>> {
    const { client: request = this.client, ...config } = options

    return request({ method: 'GET', url: '/pet/{petId}', ...config }) as Promise<RequestResult<GetPetByIdResponses, ThrowOnError>>
  }
}
usage.ts
typescript
import { PetClient } from './src/gen/clients/petClient'

const pet = new PetClient({ baseURL: 'https://petstore.example.com' })

const { data } = await pet.getPetById({ path: { petId: 1 } })
console.log(data.name)