Convert Figma logo to code with AI

openapi-ts logoopenapi-typescript

Generate TypeScript types from OpenAPI 3 specs

7,068
551
7,068
175

Top Related Projects

Generate the API Client for Fetch or Axios from an OpenAPI Specification

Generate TypeScript types from OpenAPI 3 specs

Generate TypeScript types from OpenAPI 3 specs

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

7,118

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

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

Quick Overview

openapi-ts/openapi-typescript is a TypeScript code generator that converts OpenAPI 3.0 and Swagger 2.0 schemas into TypeScript interfaces. It provides type-safe API contracts for frontend and backend developers, enhancing code quality and reducing runtime errors.

Pros

  • Generates accurate TypeScript types from OpenAPI/Swagger schemas
  • Supports both OpenAPI 3.0 and Swagger 2.0 specifications
  • Offers customization options for output formatting and type generation
  • Integrates well with popular API development workflows

Cons

  • Limited support for complex schema structures or edge cases
  • May require manual adjustments for certain API designs
  • Learning curve for advanced customization options
  • Dependency on up-to-date and well-defined OpenAPI/Swagger schemas

Code Examples

  1. Basic usage with a local OpenAPI file:
import { parse } from 'openapi-typescript';
import * as fs from 'fs';

const schema = fs.readFileSync('openapi.yaml', 'utf8');
const output = await parse(schema);
console.log(output);
  1. Generating types from a remote OpenAPI URL:
import { parse } from 'openapi-typescript';

const url = 'https://api.example.com/openapi.json';
const output = await parse(url);
console.log(output);
  1. Customizing output with options:
import { parse } from 'openapi-typescript';

const schema = `
openapi: 3.0.0
info:
  title: Example API
  version: 1.0.0
paths:
  /users:
    get:
      responses:
        '200':
          content:
            application/json:    
              schema:
                type: array
                items:
                  type: object
                  properties:
                    id: 
                      type: integer
                    name:
                      type: string
`;

const output = await parse(schema, {
  prettier: true,
  transform: (schemaObject) => {
    if (schemaObject.type === 'integer') {
      return 'number';
    }
  },
});
console.log(output);

Getting Started

  1. Install the package:

    npm install openapi-typescript
    
  2. Create a TypeScript file (e.g., generate-types.ts):

    import { parse } from 'openapi-typescript';
    import * as fs from 'fs';
    
    async function generateTypes() {
      const schema = fs.readFileSync('openapi.yaml', 'utf8');
      const output = await parse(schema);
      fs.writeFileSync('api-types.ts', output);
    }
    
    generateTypes();
    
  3. Run the script:

    ts-node generate-types.ts
    

This will generate TypeScript interfaces based on your OpenAPI schema and save them to api-types.ts.

Competitor Comparisons

Generate the API Client for Fetch or Axios from an OpenAPI Specification

Pros of swagger-typescript-api

  • Generates full API client with methods, not just types
  • Supports multiple output formats (modular, single file, etc.)
  • Includes runtime request/response validation

Cons of swagger-typescript-api

  • More complex setup and configuration
  • May generate unnecessary code for simple use cases
  • Less flexible for custom type generation

Code Comparison

swagger-typescript-api generated client:

export class Api<SecurityDataType = unknown> {
  public readonly request: HttpClient<SecurityDataType>;

  constructor(config?: Partial<ApiConfig<SecurityDataType>>) {
    this.request = new HttpClient<SecurityDataType>(config);
  }

  // ... generated API methods
}

openapi-typescript generated types:

export interface paths {
  "/users": {
    get: {
      responses: {
        200: {
          content: {
            "application/json": {
              schema: components["schemas"]["UserList"];
            };
          };
        };
      };
    };
  };
}

swagger-typescript-api focuses on generating a full API client with methods for each endpoint, while openapi-typescript generates type definitions that can be used with any HTTP client. The former provides a more complete solution out-of-the-box, while the latter offers more flexibility in implementation.

Generate TypeScript types from OpenAPI 3 specs

Pros of openapi-typescript

  • Generates TypeScript types from OpenAPI schemas
  • Supports OpenAPI 3.0 and 3.1 specifications
  • Provides CLI and programmatic usage options

Cons of openapi-typescript

  • Limited customization options for generated types
  • May not handle complex schema structures as effectively
  • Requires manual updates when API changes

Code Comparison

openapi-typescript:

import { OpenAPIV3 } from 'openapi-types';
import { parse } from 'openapi-typescript';

const schema: OpenAPIV3.Document = {
  // OpenAPI schema definition
};

const types = parse(schema);

Additional Notes

Both repositories appear to be the same project, as openapi-typescript is the main repository for the openapi-typescript package. The comparison provided above is based on the features and characteristics of the openapi-typescript project itself, rather than comparing two distinct repositories.

openapi-typescript is a popular tool for generating TypeScript types from OpenAPI schemas, offering developers a way to maintain type safety when working with API definitions. It supports both OpenAPI 3.0 and 3.1 specifications and can be used via CLI or programmatically in Node.js projects.

While it provides valuable functionality, users should be aware of its limitations in handling complex schema structures and the need for manual updates when API definitions change. Despite these considerations, openapi-typescript remains a useful tool for many developers working with OpenAPI specifications in TypeScript projects.

Generate TypeScript types from OpenAPI 3 specs

Pros of openapi-typescript

  • Generates TypeScript types from OpenAPI schemas
  • Supports OpenAPI 3.0 and 3.1 specifications
  • Provides CLI and programmatic usage options

Cons of openapi-typescript

  • Limited customization options for generated types
  • May not handle complex schema structures as effectively
  • Requires manual updates when API changes

Code Comparison

openapi-typescript:

import { OpenAPIV3 } from 'openapi-types';
import { parse } from 'openapi-typescript';

const schema: OpenAPIV3.Document = {
  // OpenAPI schema definition
};

const types = parse(schema);

Additional Notes

Both repositories appear to be the same project, as openapi-typescript is the main repository for the openapi-typescript package. The comparison provided above is based on the features and characteristics of the openapi-typescript project itself, rather than comparing two distinct repositories.

openapi-typescript is a popular tool for generating TypeScript types from OpenAPI schemas, offering developers a way to maintain type safety when working with API definitions. It supports both OpenAPI 3.0 and 3.1 specifications and can be used via CLI or programmatically in Node.js projects.

While it provides valuable functionality, users should be aware of its limitations in handling complex schema structures and the need for manual updates when API definitions change. Despite these considerations, openapi-typescript remains a useful tool for many developers working with OpenAPI specifications in TypeScript projects.

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

Pros of openapi-typescript-codegen

  • Generates complete TypeScript client code, including API classes and models
  • Supports custom templates for more flexible code generation
  • Includes built-in request handling and error management

Cons of openapi-typescript-codegen

  • May generate more code than necessary for simple use cases
  • Requires additional setup and configuration for custom templates
  • Generated code might be less flexible for manual modifications

Code Comparison

openapi-typescript:

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

openapi-typescript-codegen:

export class Pet {
  id?: number;
  name: string;
  tag?: string;

  constructor(data?: Pet) {
    if (data) {
      this.id = data.id;
      this.name = data.name;
      this.tag = data.tag;
    }
  }
}

The openapi-typescript-codegen example shows a class with a constructor, while openapi-typescript generates a simpler interface. The class-based approach provides more functionality but may be overkill for basic use cases.

7,118

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

Pros of NSwag

  • Supports multiple programming languages (C#, TypeScript, JavaScript)
  • Offers code generation for both client and server-side
  • Provides a user interface for API documentation and testing

Cons of NSwag

  • Steeper learning curve due to more extensive features
  • May generate more complex code structures
  • Requires additional setup for non-.NET environments

Code Comparison

NSwag (C# client generation):

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

openapi-typescript (TypeScript type generation):

import { parse } from 'openapi-typescript';
const schema = await parse('https://api.example.com/swagger/v1/swagger.json');

Key Differences

  • NSwag is a more comprehensive toolkit for OpenAPI, while openapi-typescript focuses specifically on TypeScript type generation
  • openapi-typescript is lighter and easier to integrate into TypeScript projects
  • NSwag offers more customization options but requires more configuration
  • openapi-typescript generates types only, while NSwag can generate full client libraries

Both tools are valuable for working with OpenAPI specifications, but they cater to different use cases and development environments.

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
  • Generates complete client libraries and server stubs
  • Offers extensive customization options and templates

Cons of openapi-generator

  • Larger and more complex, potentially slower for simple use cases
  • Steeper learning curve due to its comprehensive feature set
  • May generate unnecessary boilerplate code for smaller projects

Code comparison

openapi-generator (Java client):

OkHttpClient client = new OkHttpClient();
ApiClient apiClient = new ApiClient(client);
PetApi petApi = new PetApi(apiClient);
Pet pet = petApi.getPetById(1L);

openapi-typescript:

import { paths } from './generated';

type PetResponse = paths['/pet/{petId}']['get']['responses']['200']['content']['application/json'];
const pet: PetResponse = await fetch('/pet/1').then(res => res.json());

Key differences

  • openapi-generator provides full client libraries, while openapi-typescript focuses on type generation
  • openapi-typescript offers a more lightweight approach, suitable for TypeScript projects
  • openapi-generator supports a wider range of languages and use cases
  • openapi-typescript integrates more seamlessly with existing TypeScript codebases
  • openapi-generator may be preferred for larger, multi-language projects, while openapi-typescript is ideal for TypeScript-centric development

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

openapi-typescript

Tools for consuming OpenAPI schemas in TypeScript.

📦 Packages

openapi-typescript
Generate TypeScript types from static OpenAPI schemas

openapi-fetch
Ultra-fast fetching for TypeScript generated automatically from your OpenAPI schema.

⭐ Sponsors

🥇 Gold Sponsors

Zuplo

🥈 Silver Sponsors

nanabit

Backers

@customerio on GitHub @shaunpersad on GitHub @yoshi2no on GitHub @siketyan on GitHub

Become a sponsor by supporting this project on OpenCollective!

🤝 Contributing

Contributions are appreciated and welcome! See the appropriate guide for each package:

♥️ Thanks

NPM DownloadsLast 30 Days