or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cli-usage.mdconfiguration.mdcore-api.mdindex.mdtypes-interfaces.md
tile.json

tessl/npm-swagger-typescript-api

Generate TypeScript API clients from OpenAPI/Swagger specifications with support for Fetch and Axios HTTP clients

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/swagger-typescript-api@13.2.x

To install, run

npx @tessl/cli install tessl/npm-swagger-typescript-api@13.2.0

index.mddocs/

swagger-typescript-api

swagger-typescript-api is a TypeScript code generation tool that automatically creates API client code from OpenAPI/Swagger specifications. It supports both OpenAPI 3.0 and 2.0 in JSON and YAML formats, generating type-safe TypeScript interfaces and HTTP client implementations for both Fetch and Axios.

Package Information

  • Package Name: swagger-typescript-api
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install --save-dev swagger-typescript-api

Core Imports

import { generateApi, generateTemplates, constants } from "swagger-typescript-api";

For CommonJS:

const { generateApi, generateTemplates, constants } = require("swagger-typescript-api");

Basic Usage

Programmatic API

import { generateApi } from "swagger-typescript-api";
import * as path from "node:path";

// Generate from local file
const { files } = await generateApi({
  input: path.resolve(process.cwd(), "./swagger.json"),
  output: path.resolve(process.cwd(), "./src/api"),
  fileName: "ApiClient.ts",
  httpClientType: "fetch"
});

// Generate from URL
const result = await generateApi({
  url: "https://api.example.com/swagger.json",
  output: "./generated",
  generateResponses: true,
  generateRouteTypes: true
});

CLI Usage

# Generate from local file
npx swagger-typescript-api generate --path ./swagger.json --output ./src/api

# Generate with custom options
npx swagger-typescript-api generate \
  --path ./api-spec.yaml \
  --output ./api \
  --name ApiClient.ts \
  --axios \
  --responses \
  --route-types

Architecture

swagger-typescript-api is built around several key components:

  • Code Generation Engine: Core generateApi function that orchestrates the entire generation process
  • Schema Parser: Converts OpenAPI schemas into TypeScript type definitions with support for complex schema patterns
  • Route Generator: Creates API client methods from OpenAPI path definitions with proper parameter handling
  • Template System: EJS-based template engine allowing full customization of generated code structure
  • CLI Interface: Command-line tool with comprehensive options for build pipeline integration
  • Type Safety: Complete TypeScript type definitions throughout the generation pipeline

Capabilities

Core API Generation

Primary programmatic interface for generating TypeScript API clients from OpenAPI specifications. Supports both local files and remote URLs with extensive configuration options.

function generateApi(params: GenerateApiParams): Promise<GenerateApiOutput>;

type GenerateApiParams = 
  | GenerateApiParamsFromPath
  | GenerateApiParamsFromUrl
  | GenerateApiParamsFromSpecLiteral;

interface GenerateApiOutput {
  configuration: GenerateApiConfiguration;
  files: FileInfo[];
  createFile: (params: CreateFileParams) => void;
  renderTemplate: (templateContent: string, data: Record<string, unknown>) => Promise<string>;
  getTemplate: (params: GetTemplateParams) => string;
  formatTSContent: (content: string) => Promise<string>;
}

Core API

CLI Interface

Command-line interface providing full access to generation capabilities with comprehensive options for integration into build pipelines and development workflows.

# Main generation command
swagger-typescript-api generate [options]

# Template generation command  
swagger-typescript-api generate-templates [options]

CLI Usage

Template Generation

Generate customizable EJS templates for API code generation, allowing full control over the structure and style of generated code.

function generateTemplates(params: GenerateTemplatesParams): Promise<GenerateTemplatesOutput>;

interface GenerateTemplatesParams {
  cleanOutput?: boolean;
  output?: string;
  httpClientType?: HttpClientType;
  modular?: boolean;
  rewrite?: boolean;
  silent?: boolean;
  debug?: boolean;
}

Core API

Type Definitions & Configuration

Comprehensive TypeScript interfaces and configuration options for customizing the generation process, including hooks for advanced customization.

interface GenerateApiConfiguration {
  apiConfig: ApiConfig;
  config: GenerationConfig;
  modelTypes: ModelType[];
  routes: RouteInfo;
  utils: TemplateUtils;
}

interface Hooks {
  onInit?: (config: GenerationConfig) => GenerationConfig | undefined;
  onParseSchema?: (originalSchema: unknown, parsedSchema: unknown) => unknown | undefined;
  onCreateRoute?: (routeData: ParsedRoute) => ParsedRoute | false | undefined;
  // ... additional lifecycle hooks
}

Types & Interfaces

Configuration

Constants

Exported constants used throughout the library for configuration and schema processing.

export const constants: {
  DEFAULT_BODY_ARG_NAME: string;
  FILE_PREFIX: string;
  HTTP_CLIENT: {
    FETCH: "fetch";
    AXIOS: "axios";
  };
  PROJECT_VERSION: string;
  RESERVED_BODY_ARG_NAMES: string[];
  RESERVED_HEADER_ARG_NAMES: string[];
  RESERVED_PATH_ARG_NAMES: string[];
  RESERVED_QUERY_ARG_NAMES: string[];
  RESERVED_REQ_PARAMS_ARG_NAMES: string[];
  SCHEMA_TYPES: {
    ARRAY: "array";
    OBJECT: "object";
    ENUM: "enum";
    REF: "$ref";
    PRIMITIVE: "primitive";
    COMPLEX: "complex";
    DISCRIMINATOR: "discriminator";
    COMPLEX_ONE_OF: "oneOf";
    COMPLEX_ANY_OF: "anyOf";
    COMPLEX_ALL_OF: "allOf";
    COMPLEX_NOT: "not";
    COMPLEX_UNKNOWN: "__unknown";
  };
};

Error Handling

The library handles various error scenarios:

  • Invalid OpenAPI schemas: Detailed error messages for schema validation failures
  • Network errors: Proper handling of remote URL fetching with timeout and retry options
  • File system errors: Clear error messages for file access and write permission issues
  • Template errors: Comprehensive error reporting for template processing failures

Most functions throw descriptive errors that can be caught and handled in your application code.