Swagger TypeScript API Client Generator

13.6.10 · active · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically generate a Fetch-based API client from a local `swagger.json` file, outputting it to a specified directory.

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();

view raw JSON →