Swagger TypeScript Codegen

3.2.4 · maintenance · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

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.

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.`);
  }
}

view raw JSON →