OpenAPI to TypeScript Type Generator

7.13.0 · active · verified Sun Apr 19

openapi-typescript is a powerful command-line tool and library designed to convert OpenAPI 3.0 and 3.1 specifications into TypeScript type definitions. It produces runtime-free, statically-analyzable types, enabling robust type safety for API clients, facilitating validation of mock data, and streamlining the development of business logic directly from your API's schema. The current stable version is 7.13.0, and the project maintains a healthy and active release cadence, frequently publishing minor or patch versions across its ecosystem of packages (e.g., openapi-typescript, openapi-fetch). A key differentiator is its speed and its minimal dependency footprint, requiring only Node.js and avoiding external runtimes like Java, making it a lightweight and efficient alternative to many traditional OpenAPI codegen solutions. It supports loading schemas from local YAML or JSON files, as well as remote URLs.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to generate TypeScript types from an OpenAPI schema using the `openapi-typescript` CLI and then how to import and use the generated `paths` and `components` types in a TypeScript application to ensure type safety for API interactions. It fetches a remote Swagger Petstore schema for demonstration.

import { createClient } from '@hey-api/openapi-ts'; // For programmatic usage
import { writeFile } from 'node:fs/promises';
import type { paths, components } from './generated-api-types'; // Example usage of generated types

async function generateAndUseTypes() {
  // 1. Generate types using the CLI (most common)
  console.log('Generating types via CLI...');
  try {
    const { execa } = await import('execa');
    await execa('npx', [
      'openapi-typescript',
      'https://petstore.swagger.io/v2/swagger.json', // Or a local file: './path/to/my/schema.yaml'
      '-o',
      './generated-api-types.d.ts',
    ], { stdio: 'inherit' });
    console.log('Types generated successfully to generated-api-types.d.ts');

    // 2. Or, programmatically (uncomment to use)
    // const petstoreSchema = await (await fetch('https://petstore.swagger.io/v2/swagger.json')).json();
    // const types = await openapiTS(petstoreSchema);
    // await writeFile('./generated-api-types.d.ts', types);
    // console.log('Types generated programmatically to generated-api-types.d.ts');

    // 3. Example usage of generated types in your application
    type Pet = components['schemas']['Pet'];
    type CreatePetRequest = paths['/pet']['post']['requestBody']['content']['application/json'];
    type GetPetByIdResponse = paths['/pet/{petId}']['get']['responses']['200']['schema'];

    const myPet: Pet = {
      id: 1,
      name: 'Buddy',
      status: 'available',
      category: { id: 101, name: 'Dogs' },
      photoUrls: ['http://example.com/buddy.jpg']
    };
    console.log('Example Pet type:', myPet);

    const newPetRequest: CreatePetRequest = {
      name: 'Fluffy',
      photoUrls: ['http://example.com/fluffy.png'],
      tags: [{ id: 1, name: 'cute' }]
    };
    console.log('Example CreatePetRequest type:', newPetRequest);

  } catch (error) {
    console.error('Error during type generation or usage:', error);
    process.exit(1);
  }
}

generateAndUseTypes();

view raw JSON →