Convert Figma logo to code with AI

ferdikoomen logoopenapi-typescript-codegen

NodeJS library that generates Typescript or Javascript clients based on the OpenAPI specification

3,178
534
3,178
251

Top Related Projects

swagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)

7,002

The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.

4,532

Turn any OpenAPI2/3 and Postman Collection file into an API server with mocking, transformations and validations.

24,345

📘 OpenAPI/Swagger-generated API Reference Documentation

A node package wrapper for https://github.com/OpenAPITools/openapi-generator

Quick Overview

OpenAPI TypeScript Codegen is a tool that generates TypeScript clients based on OpenAPI 3.0 and Swagger 2.0 specifications. It aims to provide strongly typed API clients with minimal dependencies, making it easier to integrate and use APIs in TypeScript projects.

Pros

  • Generates strongly typed TypeScript clients for improved type safety and developer experience
  • Supports both OpenAPI 3.0 and Swagger 2.0 specifications
  • Produces minimal dependencies, resulting in smaller bundle sizes
  • Offers customization options for generated code

Cons

  • May require manual adjustments for complex API structures or edge cases
  • Generated code might not cover all possible API scenarios out of the box
  • Learning curve for understanding and customizing the generated code
  • Limited support for certain advanced OpenAPI features

Code Examples

  1. Generate TypeScript client from an OpenAPI specification:
import { generate } from 'openapi-typescript-codegen';

generate({
  input: './openapi.json',
  output: './src/api',
  httpClient: 'fetch',
});
  1. Use the generated API client:
import { ApiClient, Pet } from './api';

const api = new ApiClient();

async function getPet(petId: number): Promise<Pet> {
  const response = await api.pet.getPetById(petId);
  return response;
}
  1. Custom configuration for generated client:
import { generate } from 'openapi-typescript-codegen';

generate({
  input: './openapi.yaml',
  output: './src/api',
  httpClient: 'axios',
  useOptions: true,
  useUnionTypes: true,
});

Getting Started

  1. Install the package:
npm install openapi-typescript-codegen
  1. Generate TypeScript client:
import { generate } from 'openapi-typescript-codegen';

generate({
  input: 'https://petstore3.swagger.io/api/v3/openapi.json',
  output: './src/api',
  httpClient: 'fetch',
});
  1. Use the generated client in your TypeScript project:
import { ApiClient } from './api';

const api = new ApiClient();
api.pet.getPetById(1).then(pet => console.log(pet));

Competitor Comparisons

swagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.

Pros of swagger-codegen

  • Supports multiple programming languages and frameworks
  • Extensive customization options through templates
  • Large community and ecosystem with many plugins and extensions

Cons of swagger-codegen

  • Can be complex to set up and configure
  • May generate more boilerplate code
  • Slower generation process, especially for large APIs

Code Comparison

openapi-typescript-codegen:

import { ApiClient, Pet } from './generated';

const api = new ApiClient();
const pet = await api.pet.getPetById(1);
console.log(pet.name);

swagger-codegen:

import io.swagger.client.*;
import io.swagger.client.api.PetApi;
import io.swagger.client.model.Pet;

ApiClient client = new ApiClient();
PetApi api = new PetApi(client);
Pet pet = api.getPetById(1L);
System.out.println(pet.getName());

openapi-typescript-codegen focuses on TypeScript and generates more concise, type-safe code. swagger-codegen provides a more verbose output but offers support for multiple languages. The openapi-typescript-codegen example demonstrates a more straightforward API usage, while swagger-codegen requires more setup and configuration.

Both tools have their strengths, with openapi-typescript-codegen being more specialized for TypeScript projects and swagger-codegen offering broader language support and customization options.

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)

Pros of openapi-generator

  • Supports multiple programming languages and frameworks
  • Extensive customization options and templates
  • Large community and active development

Cons of openapi-generator

  • Steeper learning curve due to its complexity
  • Can be slower for simple projects
  • May generate more boilerplate code

Code Comparison

openapi-typescript-codegen:

export interface Pet {
    id?: number;
    name: string;
    tag?: string;
}

openapi-generator:

export interface Pet {
    id?: number;
    name: string;
    tag?: string;
}

export class PetApi {
    constructor(protected httpClient: HttpClient) {}

    public getPetById(petId: number): Observable<Pet> {
        // Implementation details
    }
}

The code generated by openapi-generator tends to include more structure and helper methods, while openapi-typescript-codegen focuses on generating simpler, more lightweight interfaces.

openapi-generator is better suited for complex projects requiring multi-language support and extensive customization. It offers a wide range of features but may be overkill for smaller TypeScript-only projects.

openapi-typescript-codegen is ideal for TypeScript-specific projects, providing a simpler and faster solution with less overhead. It generates clean, lightweight code but lacks the versatility of openapi-generator for multi-language support.

7,002

The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.

Pros of NSwag

  • Supports multiple programming languages and frameworks, including C#, TypeScript, and Angular
  • Offers a more comprehensive set of features, including API documentation generation and server-side code generation
  • Provides a user-friendly GUI tool for easier configuration and code generation

Cons of NSwag

  • May have a steeper learning curve due to its broader feature set
  • Can be more resource-intensive and slower for large API specifications
  • Less focused on TypeScript-specific optimizations compared to openapi-typescript-codegen

Code Comparison

NSwag (TypeScript client generation):

var document = await OpenApiDocument.FromUrlAsync("https://api.example.com/swagger/v1/swagger.json");
var settings = new TypeScriptClientGeneratorSettings();
var generator = new TypeScriptClientGenerator(document, settings);
var code = generator.GenerateFile();

openapi-typescript-codegen:

import { generate } from 'openapi-typescript-codegen';

await generate({
  input: 'https://api.example.com/swagger/v1/swagger.json',
  output: './generated',
  httpClient: 'fetch',
});

Both tools generate TypeScript clients from OpenAPI specifications, but NSwag offers more configuration options and supports multiple languages, while openapi-typescript-codegen is more focused on TypeScript and provides a simpler API for code generation.

4,532

Turn any OpenAPI2/3 and Postman Collection file into an API server with mocking, transformations and validations.

Pros of Prism

  • Offers API mocking and contract testing capabilities
  • Supports multiple specification formats (OpenAPI, Postman Collections)
  • Provides a CLI tool for easy integration into workflows

Cons of Prism

  • Primarily focused on API mocking and testing, not code generation
  • May require additional setup for TypeScript integration
  • Less specialized for TypeScript-specific use cases

Code Comparison

While a direct code comparison isn't relevant due to the different focus areas of these projects, here's a brief example of how they might be used:

Prism (API mocking):

prism mock api.yaml

openapi-typescript-codegen (TypeScript generation):

openapi --input api.yaml --output ./generated

Summary

Prism is a versatile tool for API mocking and testing, supporting multiple specification formats and offering a CLI for easy integration. However, it's not specifically designed for TypeScript code generation. openapi-typescript-codegen, on the other hand, is specialized for generating TypeScript code from OpenAPI specifications, making it more suitable for projects requiring TypeScript-specific output. The choice between these tools depends on whether the primary need is API mocking and testing (Prism) or TypeScript code generation (openapi-typescript-codegen).

24,345

📘 OpenAPI/Swagger-generated API Reference Documentation

Pros of Redoc

  • Provides a beautiful, customizable API documentation interface
  • Supports multiple themes and responsive design for various devices
  • Offers interactive API console for testing endpoints directly from the documentation

Cons of Redoc

  • Focused on documentation rendering, not code generation
  • May require additional tools for TypeScript integration
  • Less suitable for generating client-side API wrappers

Code Comparison

Redoc (HTML embedding):

<script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script>
<redoc spec-url="https://api.example.com/openapi.json"></redoc>

openapi-typescript-codegen (TypeScript generation):

import { OpenAPI } from './generated';

const api = new OpenAPI({
  BASE: 'https://api.example.com',
  TOKEN: 'your-access-token'
});

const result = await api.users.getUser(123);

While Redoc excels in creating visually appealing API documentation, openapi-typescript-codegen focuses on generating TypeScript code for API interactions. Redoc is ideal for teams needing comprehensive, user-friendly documentation, whereas openapi-typescript-codegen is better suited for developers looking to integrate API calls directly into their TypeScript projects with type safety and auto-completion.

A node package wrapper for https://github.com/OpenAPITools/openapi-generator

Pros of openapi-generator-cli

  • Supports multiple programming languages and frameworks
  • Offers a wide range of customization options
  • Has a large community and extensive documentation

Cons of openapi-generator-cli

  • Can be complex to set up and configure
  • May generate more boilerplate code
  • Slower generation process for large APIs

Code Comparison

openapi-generator-cli:

openapi-generator generate -i openapi.yaml -g typescript-axios -o ./generated

openapi-typescript-codegen:

openapi --input openapi.yaml --output ./generated

Additional Notes

openapi-generator-cli is a more comprehensive tool that supports various languages and frameworks, making it suitable for complex, multi-language projects. It offers extensive customization options but may require more setup time.

openapi-typescript-codegen is focused solely on TypeScript, providing a simpler and faster generation process for TypeScript projects. It generates cleaner code with fewer dependencies but lacks the versatility of openapi-generator-cli.

Both tools are actively maintained and have their strengths. The choice between them depends on project requirements, team expertise, and the need for multi-language support versus TypeScript-specific optimization.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Important announcement

[!IMPORTANT] Please migrate your projects to use @hey-api/openapi-ts

Due to time limitations on my end, this project has been unmaintained for a while now. The @hey-api/openapi-ts project started as a fork with the goal to resolve the most pressing issues. going forward they are planning to maintain the OpenAPI generator and give it the love it deserves. Please support them with their work and make sure to migrate your projects: https://heyapi.dev/openapi-ts/migrating.html#openapi-typescript-codegen

  • All open PR's and issues will be archived on the 1st of May 2024
  • All versions of this package will be deprecated in NPM

👋 Thanks for all the support, downloads and love! Cheers Ferdi.


OpenAPI Typescript Codegen

NPM License Downloads Build

Node.js library that generates Typescript clients based on the OpenAPI specification.

Why?

  • Frontend ❤️ OpenAPI, but we do not want to use JAVA codegen in our builds
  • Quick, lightweight, robust and framework-agnostic 🚀
  • Supports generation of TypeScript clients
  • Supports generations of Fetch, Node-Fetch, Axios, Angular and XHR http clients
  • Supports OpenAPI specification v2.0 and v3.0
  • Supports JSON and YAML files for input
  • Supports generation through CLI, Node.js and NPX
  • Supports tsc and @babel/plugin-transform-typescript
  • Supports aborting of requests (cancelable promise pattern)
  • Supports external references using json-schema-ref-parser

Install

npm install openapi-typescript-codegen --save-dev

Usage

$ openapi --help

  Usage: openapi [options]

  Options:
    -V, --version             output the version number
    -i, --input <value>       OpenAPI specification, can be a path, url or string content (required)
    -o, --output <value>      Output directory (required)
    -c, --client <value>      HTTP client to generate [fetch, xhr, node, axios, angular] (default: "fetch")
    --name <value>            Custom client class name
    --useOptions              Use options instead of arguments
    --useUnionTypes           Use union types instead of enums
    --exportCore <value>      Write core files to disk (default: true)
    --exportServices <value>  Write services to disk (default: true)
    --exportModels <value>    Write models to disk (default: true)
    --exportSchemas <value>   Write schemas to disk (default: false)
    --indent <value>          Indentation options [4, 2, tab] (default: "4")
    --postfixServices         Service name postfix (default: "Service")
    --postfixModels           Model name postfix
    --request <value>         Path to custom request file
    -h, --help                display help for command

  Examples
    $ openapi --input ./spec.json --output ./generated
    $ openapi --input ./spec.json --output ./generated --client xhr

Documentation

The main documentation can be found in the openapi-typescript-codegen/wiki

Sponsors

If you or your company use the OpenAPI Typescript Codegen, please consider supporting me. By sponsoring I can free up time to give this project some love! Details can be found here: https://github.com/sponsors/ferdikoomen

If you're from an enterprise looking for a fully managed SDK generation, please consider our sponsor:

speakeasy

NPM DownloadsLast 30 Days