Skip to main content

Programmatic Usage

While the CLI is the most common way to use OpenAPI TypeScript, you can also use it programmatically in Node.js applications, custom build scripts, or integration with other tools.

The createClient API

The createClient function is the main programmatic interface. It accepts a configuration object (or array of configurations) and returns a Promise that resolves to an array of generation contexts.

Basic Usage

Function Signature

The createClient function is defined in /home/daytona/workspace/source/packages/openapi-ts/src/generate.ts:32:
Parameters:
  • userConfig - Single config, array of configs, or lazy function returning config(s)
  • logger - Optional custom Logger instance for controlling output
Returns:
  • Array of Context objects containing the generation results

Configuration Options

The programmatic API accepts the same configuration as openapi-ts.config.ts files. Use the defineConfig helper for type safety:

Multiple Configurations

Generate multiple clients in a single call:

Lazy Configuration

Use a function for dynamic configuration:

Custom Logging

Control logging output with a custom Logger:

Error Handling

Handle errors during generation:

Integration Examples

Build Script

Integrate with your build process:
scripts/generate-client.ts
Add to package.json:

Vite Plugin

Create a Vite plugin for development:
vite-plugin-openapi.ts

Next.js Integration

Generate client before Next.js builds:
scripts/setup.ts

Custom Plugin Loader

Dynamically load plugins based on environment:

Working with the Context

The returned Context object contains information about the generation:

Dry Run Mode

Test generation without writing files:

Advanced: Custom File Generation

Access the generation pipeline for custom processing:

TypeScript Configuration

When using programmatically, ensure your tsconfig.json supports ESM:
tsconfig.json

Best Practices

Next Steps

Custom Plugins

Build custom plugins to extend code generation

Watch Mode

Configure automatic regeneration on file changes