Swagger TypeScript API Client Generator
The `swagger-typescript-api` package is a code generation utility designed to create API client code and comprehensive TypeScript types directly from an OpenAPI Specification (Swagger) document. It offers robust support for both OpenAPI 3.0 and 2.0 definitions, handling specifications provided in JSON or YAML formats. Developers can configure the generated client to utilize either the native Fetch API or the widely-used Axios library, catering to diverse project requirements and existing HTTP client preferences. Currently at version 13.6.10, the project demonstrates an active development lifecycle with consistent patch releases that address bugs and introduce minor features. Its key differentiators include generating fully type-safe API interfaces, reducing manual boilerplate, and enabling a streamlined development workflow for interacting with RESTful APIs in TypeScript-driven applications, ensuring better maintainability and fewer runtime errors.
Common errors
-
ERR_PACKAGE_PATH_NOT_EXPORTED: No "exports" main defined in eta/package.json
cause A dependency conflict or premature upgrade of the `eta` templating engine, specifically `eta@4.0.1`, which had an incorrect package export configuration.fixThis was internally fixed by downgrading `eta` to `3.5.0`. Ensure you are on a `swagger-typescript-api` version that has this fix (e.g., `13.2.15` or newer). -
Property 'someProperty' does not exist on type 'SomeType'.
cause Mismatch between the OpenAPI specification and the generated TypeScript types, often due to complex schema structures, `oneOf`/`anyOf`/`allOf` issues, or incorrect handling of nullable fields.fixReview your OpenAPI specification for correctness and consistency. Utilize `swagger-typescript-api` options like `extractEnums`, `extractRequestBody`, `extractResponseBody`, and `primitiveTypeConstructs` to fine-tune type generation. Consider using `prettier` post-generation to catch syntax issues. -
TypeScript syntax errors in generated client, e.g., 'Expected ;' or 'Expression expected.'
cause Issues with specific template logic, especially with modular templates or custom template modifications, which can result in malformed TypeScript output.fixVerify the `swagger-typescript-api` version; if using an older version (e.g., 13.2.8-13.2.12) which had known modular template bugs, upgrade. If using custom templates, carefully review the `.eta` files for syntax errors or incorrect output patterns.
Warnings
- breaking The package now explicitly requires Node.js version 20 or higher. Users on older Node.js versions will encounter compatibility issues or installation failures.
- breaking The signature for the `securityWorker` function, used in custom `http-client.eta` templates, changed in v10.0.0. It now supports returning a `Promise<RequestParams | void>` in addition to `RequestParams | void`.
- breaking Versions 13.2.8 through 13.2.12 had issues generating invalid TypeScript code when using modular templates, specifically with object method syntax (`:` and `,`) instead of class property syntax (`=` and `;`).
- gotcha When using custom templates (e.g., `.eta` files), the generator automatically removes `import` statements for symbols that are not explicitly used within the template. This can lead to confusion if an import is intended for global types or future use.
- gotcha When generating multiple API clients programmatically, using the `config` object for custom properties can lead to unexpected behavior due to its global reference. Subsequent generations might use outdated `config` values.
Install
-
npm install swagger-typescript-api -
yarn add swagger-typescript-api -
pnpm add swagger-typescript-api
Imports
- generateApi
const { generateApi } = require('swagger-typescript-api');import { generateApi } from 'swagger-typescript-api'; - CLI Usage
node_modules/swagger-typescript-api/lib/cli.js generate --path ./swagger.json
npx swagger-typescript-api generate --path ./swagger.json
- API Options
import type { IExtendedOptions } from 'swagger-typescript-api';
Quickstart
import * as path from "node:path";
import * as process from "node:process";
import { generateApi } from "swagger-typescript-api";
const swaggerSpecPath = path.resolve(process.cwd(), "./swagger.json");
const outputPath = path.resolve(process.cwd(), "./src/api");
// A minimal example showing how to generate an API client
// Ensure a swagger.json file exists in the current working directory
// For more complex configurations (e.g., custom templates, Axios vs Fetch),
// refer to the official documentation and API options.
async function main() {
try {
await generateApi({
name: "Api.ts", // Output file name
output: outputPath, // Output directory
input: swaggerSpecPath, // Path to OpenAPI/Swagger JSON/YAML file
httpClient: "fetch", // Or 'axios'
generateClient: true, // Whether to generate the client methods
extractEnums: true, // Extract enums to separate types
moduleNameFirstTag: true, // Group operations by the first tag in the module name
});
console.log(`API client successfully generated at ${outputPath}/Api.ts`);
} catch (error) {
console.error("Error generating API client:", error);
process.exit(1);
}
}
main();