{"id":15847,"library":"swagger-typescript-codegen","title":"Swagger TypeScript Codegen","description":"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.","status":"maintenance","version":"3.2.4","language":"javascript","source_language":"en","source_url":"git://github.com/mtennoe/swagger-typescript-codegen","tags":["javascript","swagger","rest"],"install":[{"cmd":"npm install swagger-typescript-codegen","lang":"bash","label":"npm"},{"cmd":"yarn add swagger-typescript-codegen","lang":"bash","label":"yarn"},{"cmd":"pnpm add swagger-typescript-codegen","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Used as the underlying HTTP client for generated TypeScript code.","package":"superagent","optional":false},{"reason":"Used for beautifying generated code if the `beautify` option is enabled.","package":"js-beautify","optional":true}],"imports":[{"note":"The primary API is exposed via CommonJS `require` for `CodeGen.getTypescriptCode` and `CodeGen.getCustomCode`. While an ES module import might be attempted, it is not the documented or typical usage.","wrong":"import { CodeGen } from 'swagger-typescript-codegen';","symbol":"CodeGen","correct":"const CodeGen = require('swagger-typescript-codegen').CodeGen;"},{"note":"This is a static method of the `CodeGen` object, not a top-level named export. It must be called on the imported `CodeGen` object.","wrong":"import { getTypescriptCode } from 'swagger-typescript-codegen';","symbol":"getTypescriptCode","correct":"CodeGen.getTypescriptCode({ /* options */ });"},{"note":"Similar to `getTypescriptCode`, this is a static method of the `CodeGen` object used for custom template-based generation and must be called on the imported `CodeGen` object.","wrong":"import { getCustomCode } from 'swagger-typescript-codegen';","symbol":"getCustomCode","correct":"CodeGen.getCustomCode({ /* options */ });"}],"quickstart":{"code":"var fs = require(\"fs\");\nvar CodeGen = require(\"swagger-typescript-codegen\").CodeGen;\n\n// Assuming 'swagger/spec.json' exists in the project root\n// or provide an absolute path.\nvar swaggerFilePath = \"swagger/spec.json\";\n\ntry {\n  var swagger = JSON.parse(fs.readFileSync(swaggerFilePath, \"UTF-8\"));\n  var tsSourceCode = CodeGen.getTypescriptCode({\n    className: \"TestClient\", // Renamed for clarity\n    swagger: swagger,\n    // Example of importing a typings file if needed, adjust path as necessary\n    imports: [\"./typings/my-custom-types.d.ts\"]\n  });\n  console.log(tsSourceCode);\n} catch (error) {\n  console.error(`Failed to generate code: ${error.message}`);\n  if (error.code === 'ENOENT') {\n    console.error(`Ensure '${swaggerFilePath}' exists and is accessible.`);\n  } else if (error instanceof SyntaxError) {\n    console.error(`Swagger file '${swaggerFilePath}' is not valid JSON.`);\n  }\n}","lang":"javascript","description":"This snippet demonstrates how to synchronously load a Swagger JSON specification from a file, parse it, and then use `swagger-typescript-codegen` to generate a TypeScript client class named 'TestClient', logging the output to the console."},"warnings":[{"fix":"Ensure your input specification strictly adheres to Swagger 2.0. If using OpenAPI 3.x, thoroughly test the generated code for correctness or consider alternative tools designed specifically for OpenAPI 3.x.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Utilize the `CodeGen.getCustomCode` function with tailored Mustache templates (`class`, `method`, `type`) to generate code that incorporates your desired HTTP client and its API calls.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For actual module dependencies of the generated client (e.g., `superagent` itself if not bundled), you will need to manually ensure they are installed and correctly bundled/imported in your consuming application. The `imports` option specifically handles type references.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Stick to `const CodeGen = require('swagger-typescript-codegen').CodeGen;` for consistent and reliable module loading, especially in Node.js environments. If working in a pure ESM context, manual wrapping or careful configuration might be needed.","message":"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.","severity":"deprecated","affected_versions":"3.x"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Verify 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`.","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.","error":"TypeError: Cannot read properties of undefined (reading 'info')"},{"fix":"Use 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.","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.","error":"TypeError: CodeGen.getTypescriptCode is not a function"},{"fix":"Double-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.","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.","error":"Error: ENOENT: no such file or directory, open 'swagger/spec.json'"}],"ecosystem":"npm"}