Swagger TypeScript Codegen
This package, currently at version 3.2.4, generates TypeScript client code from a Swagger/OpenAPI 2.0 specification file. It leverages Mustache templates for highly customizable code generation, allowing developers to define their own class, method, and type structures. The generated code is built upon `superagent` for HTTP requests, making it adaptable for both Node.js and browser environments when used with bundlers like Browserify or Webpack. The project originated as a fork to streamline specific functionalities and integrate code quality checks via JSHint and code beautification with JS-Beautify. While not indicating a rapid release cadence, its focus on customization and robust template-driven generation makes it suitable for projects requiring tailored API clients.
Common errors
-
TypeError: Cannot read properties of undefined (reading 'info')
cause The provided `swagger` object is malformed, missing the crucial `info` property, or the file failed to load/parse correctly resulting in an empty or invalid object.fixVerify the `swagger` JSON file's content and structure against the Swagger 2.0 specification. Ensure `fs.readFileSync` successfully reads the file and `JSON.parse` does not throw an error before passing the object to `CodeGen`. -
TypeError: CodeGen.getTypescriptCode is not a function
cause Incorrectly importing or accessing the `CodeGen` object, often due to trying a default ESM import (`import CodeGen from '...'`) or an incorrect named import that doesn't resolve the static methods.fixUse the documented CommonJS import pattern: `const CodeGen = require('swagger-typescript-codegen').CodeGen;` to ensure `CodeGen` is correctly resolved as an object with the static `getTypescriptCode` method. -
Error: ENOENT: no such file or directory, open 'swagger/spec.json'
cause The specified Swagger specification file (`swagger/spec.json` in the example) does not exist at the given path relative to where the script is being executed.fixDouble-check the file path provided to `fs.readFileSync`. Ensure the file exists and the path is correct, or use an absolute path for robustness. Consider adding `process.cwd()` to construct the full path.
Warnings
- gotcha This tool is primarily designed for Swagger 2.0 specifications (OpenAPI 2.0). While it might process some OpenAPI 3.x definitions, full compatibility is not guaranteed, and unexpected behavior or missing features may occur.
- gotcha The generated TypeScript code relies on `superagent` for HTTP requests. If your project uses a different HTTP client (e.g., Axios, Fetch API), you will need to provide custom templates to integrate your preferred client library, or manually adjust the generated code.
- gotcha The `imports` option in `getTypescriptCode` is strictly for adding TypeScript definition file (`.d.ts`) imports or `/// <reference />` directives for type augmentation, not for importing JavaScript modules that the generated client might depend on.
- deprecated The primary usage examples and documentation show `require` for importing `CodeGen`. While Node.js supports ESM, the package's direct usage of `require` for its exports suggests a CJS-first design. Attempting ESM imports like `import { CodeGen } from 'swagger-typescript-codegen'` might not work or could require specific Node.js loader configurations.
Install
-
npm install swagger-typescript-codegen -
yarn add swagger-typescript-codegen -
pnpm add swagger-typescript-codegen
Imports
- CodeGen
import { CodeGen } from 'swagger-typescript-codegen';const CodeGen = require('swagger-typescript-codegen').CodeGen; - getTypescriptCode
import { getTypescriptCode } from 'swagger-typescript-codegen';CodeGen.getTypescriptCode({ /* options */ }); - getCustomCode
import { getCustomCode } from 'swagger-typescript-codegen';CodeGen.getCustomCode({ /* options */ });
Quickstart
var fs = require("fs");
var CodeGen = require("swagger-typescript-codegen").CodeGen;
// Assuming 'swagger/spec.json' exists in the project root
// or provide an absolute path.
var swaggerFilePath = "swagger/spec.json";
try {
var swagger = JSON.parse(fs.readFileSync(swaggerFilePath, "UTF-8"));
var tsSourceCode = CodeGen.getTypescriptCode({
className: "TestClient", // Renamed for clarity
swagger: swagger,
// Example of importing a typings file if needed, adjust path as necessary
imports: ["./typings/my-custom-types.d.ts"]
});
console.log(tsSourceCode);
} catch (error) {
console.error(`Failed to generate code: ${error.message}`);
if (error.code === 'ENOENT') {
console.error(`Ensure '${swaggerFilePath}' exists and is accessible.`);
} else if (error instanceof SyntaxError) {
console.error(`Swagger file '${swaggerFilePath}' is not valid JSON.`);
}
}