# openapi-typescript **Repository Path**: mirrors_Semigradsky/openapi-typescript ## Basic Information - **Project Name**: openapi-typescript - **Description**: Generate TypeScript types from Swagger OpenAPI specs - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2022-10-24 - **Last Updated**: 2026-03-22 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README [![version(scoped)](https://img.shields.io/npm/v/openapi-typescript.svg)](https://www.npmjs.com/package/openapi-typescript) [![npm downloads (weekly)](https://img.shields.io/npm/dw/openapi-typescript)](https://www.npmjs.com/package/openapi-typescript) [![codecov](https://codecov.io/gh/drwpow/openapi-typescript/branch/main/graph/badge.svg)](https://codecov.io/gh/drwpow/openapi-typescript) [![All Contributors](https://img.shields.io/badge/all_contributors-53-orange.svg?style=flat-square)](#contributors-) # πŸ“˜οΈ openapi-typescript πŸš€ Convert [OpenAPI 3.0][openapi3] and [2.0 (Swagger)][openapi2] schemas to TypeScript interfaces using Node.js. **Features** - βœ… [OpenAPI 3.0][openapi3] - βœ… [Swagger 2.0][openapi2] - βœ… Supports YAML and JSON schema formats - βœ… Supports loading via remote URL (simple authentication supported with the `--auth` flag) - βœ… Supports remote references: `$ref: "external.yaml#components/schemas/User"` - βœ… Formats using [Prettier][prettier] - βœ… TypeScript 4.0 features **Examples** - [Stripe, OpenAPI 2.0](./examples/stripe-openapi2.ts) - [Stripe, OpenAPI 3.0](./examples/stripe-openapi3.ts) ## Usage ### πŸ–₯️ CLI #### πŸ—„οΈ Reading specs from file system ```bash npx openapi-typescript schema.yaml --output schema.ts # πŸ”­ Loading spec from schema.yaml… # πŸš€ schema.yaml -> schema.ts [250ms] npx openapi-typescript "specs/**/*.yaml" --output schemas/ # πŸ”­ Loading spec from specs/one.yaml… # πŸ”­ Loading spec from specs/two.yaml… # πŸ”­ Loading spec from specs/three.yaml… # πŸš€ specs/one.yaml -> schemas/specs/one.ts [250ms] # πŸš€ specs/two.yaml -> schemas/specs/two.ts [250ms] # πŸš€ specs/three.yaml -> schemas/specs/three.ts [250ms] ``` _Note: if generating a single schema, `--output` must be a file (preferably `*.ts`). If using globs, `--output` must be a directory._ _Thanks to [@sharmarajdaksh](https://github.com/sharmarajdaksh) for the glob feature!_ #### ☁️ Reading specs from remote resource ```bash npx openapi-typescript https://petstore.swagger.io/v2/swagger.json --output petstore.ts # πŸ”­ Loading spec from https://petstore.swagger.io/v2/swagger.json… # πŸš€ https://petstore.swagger.io/v2/swagger.json -> petstore.ts [650ms] ``` _Note: globbing doesn’t work for remote schemas because there is no reliable way to determine a list of files to select from a remote file system._ _Thanks to [@psmyrdek](https://github.com/psmyrdek) for the remote spec feature!_ #### Using in TypeScript Import any top-level item from the generated spec to use it. It works best if you also alias types to save on typing: ```ts import { components } from "./generated-schema.ts"; type APIResponse = components["schemas"]["APIResponse"]; ``` Because OpenAPI schemas may have invalid TypeScript characters as names, the square brackets are a safe way to access every property. Also note that there’s a special `operations` interface that you can import `OperationObjects` by their [operationId][openapi-operationid]: ```ts import { operations } from "./generated-schema.ts"; type getUsersById = operations["getUsersById"]; ``` Even though `operations` isn’t present in your original schema, it’s a simple convenience and won’t disrupt any of your other types. _Thanks to [@gr2m](https://github.com/gr2m) for the operations feature!_ #### openapi-typescript-fetch The generated spec can also be used with [openapi-typescript-fetch](https://www.npmjs.com/package/openapi-typescript-fetch) which implements a typed fetch client for openapi-typescript. ```ts import { paths } from "./petstore"; import { Fetcher } from "openapi-typescript-fetch"; // declare fetcher for paths const fetcher = Fetcher.for() // global configuration fetcher.configure({ baseUrl: "https://petstore.swagger.io/v2", init: { headers: { ... }, }, use: [...] // middlewares }) // create fetch operations const findPetsByStatus = fetcher.path("/pet/findByStatus").method("get").create() const addPet = fetcher.path("/pet").method("post").create() // fetch try { const { status, data: pets } = await findPetsByStatus({ status: ["available", "pending"], }) await addPet({ ... }) } catch(e) { // check which operation threw the exception if (e instanceof addPet.Error) { // get discriminated union { status, data } const error = e.getActualType() if (error.status === 400) { error.data.validationErrors // 400 response data } else if (error.status === 500) { error.data.errorMessage // 500 response data } else { ... } } } ``` #### Outputting to stdout Simply omit the `--output` flag to return to stdout: ```bash npx openapi-typescript schema.yaml ``` #### CLI Options | Option | Alias | Default | Description | | :----------------------------- | :---- | :------: | :-------------------------------------------------------------------------------------------------------------------------------------- | | `--output [location]` | `-o` | (stdout) | Where should the output file be saved? | | `--auth [token]` | | | (optional) Provide an auth token to be passed along in the request (only if accessing a private schema) | | `--header` | `-x` | | (optional) Provide an array of or singular headers as an alternative to a JSON object. Each header must follow the `key: value` pattern | | `--headersObject` | `-h` | | (optional) Provide a JSON object as string of HTTP headers for remote schema request. This will take priority over `--header` | | `--httpMethod` | `-m` | `GET` | (optional) Provide the HTTP Verb/Method for fetching a schema from a remote URL | | `--immutable-types` | `-it` | `false` | (optional) Generates immutable types (readonly properties and readonly array) | | `--additional-properties` | `-ap` | `false` | (optional) Allow arbitrary properties for all schema objects without `additionalProperties: false` | | `--default-non-nullable` | | `false` | (optional) Treat schema objects with default values as non-nullable | | `--prettier-config [location]` | `-c` | | (optional) Path to your custom Prettier configuration for output | | `--export-type` | | `false` | (optional) Export `type` instead of `interface` | | `--support-array-length` | | `false` | (optional) Generate tuples using array minItems / maxItems | | `--make-paths-enum` | `-pe` | `false` | (optional) Generate an enum of endpoint paths | | `--path-params-as-types` | | `false` | (optional) Substitute path parameter names with their respective types | | `--raw-schema` | | `false` | Generate TS types from partial schema (e.g. having `components.schema` at the top level) | | `--version` | | | Force OpenAPI version with `--version 3` or `--version 2` (required for `--raw-schema` when version is unknown) | ### 🐒 Node ```bash npm i --save-dev openapi-typescript ``` ```js import fs from "fs"; import openapiTS from "openapi-typescript"; // example 1: load [object] as schema (JSON only) const schema = await fs.promises.readFile("spec.json", "utf8") // must be OpenAPI JSON const output = await openapiTS(JSON.parse(schema)); // example 2: load [string] as local file (YAML or JSON; released in v4.0) const localPath = new URL("./spec.yaml", import.meta.url); // may be YAML or JSON format const output = await openapiTS(localPath); // example 3: load [string] as remote URL (YAML or JSON; released in v4.0) const output = await openapiTS("https://myurl.com/v1/openapi.yaml"); ``` The Node API may be useful if dealing with dynamically-created schemas, or you’re using within context of a larger application. Pass in either a JSON-friendly object to load a schema from memory, or a string to load a schema from a local file or remote URL (it will load the file quickly using built-in Node methods). Note that a YAML string isn’t supported in the Node.js API; either use the CLI or convert to JSON using [js-yaml][js-yaml] first. ⚠️ As of `v4.0`, `openapiTS()` is an async function. #### Custom Formatter If using the Node.js API, you can optionally pass a **formatter** to openapi-typescript. This is useful if you want to override the default types and substitute your own. For example, say your schema has the following property: ```yaml properties: updated_at: type: string format: date-time ``` By default, this will generate a type `updated_at?: string;`. But we can override this by passing a formatter to the Node API, like so: ```js const types = openapiTS(mySchema, { formatter(node: SchemaObject) { if (node.format === "date-time") { return "Date"; // return the TypeScript β€œDate” type, as a string } // for all other schema objects, let openapi-typescript decide (return undefined) }); ``` This will generate `updated_at?: Date` instead. Note that you will still have to do the parsing of your data yourself. But this will save you from having to also update all your types. _Note: you don’t have to use `.format`β€”this is just an example! You can use any property on a schema object to overwrite its generated type if desired._ ## πŸ… Project Goals 1. Support converting any OpenAPI 3.0 or 2.0 (Swagger) schema to TypeScript types, no matter how complicated 1. The generated TypeScript types **must** match your schema as closely as possible (i.e. don’t convert names to `PascalCase` or follow any TypeScript-isms; faithfully reproduce your schema as closely as possible, capitalization and all) 1. This library is a TypeScript generator, not a schema validator. ## 🀝 Contributing PRs are welcome! Please see our [CONTRIBUTING.md](./CONTRIBUTING.md) guide. Opening an issue beforehand to discuss is encouraged but not required. [glob]: https://www.npmjs.com/package/glob [js-yaml]: https://www.npmjs.com/package/js-yaml [namespace]: https://www.typescriptlang.org/docs/handbook/namespaces.html [npm-run-all]: https://www.npmjs.com/package/npm-run-all [openapi-format]: https://swagger.io/specification/#data-types [openapi-operationid]: https://swagger.io/specification/#operation-object [openapi2]: https://swagger.io/specification/v2/ [openapi3]: https://swagger.io/specification [prettier]: https://npmjs.com/prettier ### Contributors ✨ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
Drew Powers
Drew Powers

πŸ’» πŸ“– πŸš‡ ⚠️
Przemek Smyrdek
Przemek Smyrdek

πŸ’» πŸ“– πŸ€” ⚠️
Dan Enman
Dan Enman

πŸ› πŸ’»
Atle Frenvik Sveen
Atle Frenvik Sveen

πŸ’» πŸ“– πŸ€” ⚠️
Tim de Wolf
Tim de Wolf

πŸ’» πŸ€”
Tom Barton
Tom Barton

πŸ’» πŸ“– πŸ€” ⚠️
Sven Nicolai Viig
Sven Nicolai Viig

πŸ› πŸ’» ⚠️
Sorin Davidoi
Sorin Davidoi

πŸ› πŸ’» ⚠️
Nathan Schneirov
Nathan Schneirov

πŸ’» πŸ“– πŸ€” ⚠️
Lucien BΓ©niΓ©
Lucien BΓ©niΓ©

πŸ’» πŸ“– πŸ€” ⚠️
Boris K
Boris K

πŸ“–
Anton
Anton

πŸ› πŸ’» πŸ€” ⚠️
Tim Shelburne
Tim Shelburne

πŸ’» ⚠️
MichaΕ‚ Miszczyszyn
MichaΕ‚ Miszczyszyn

πŸ’»
Sam K Hall
Sam K Hall

πŸ’» ⚠️
Matt Jeanes
Matt Jeanes

πŸ’»
Kristofer Giltvedt Selbekk
Kristofer Giltvedt Selbekk

πŸ’»
Elliana May
Elliana May

πŸ’» ⚠️
Henrik Hall
Henrik Hall

πŸ’» πŸ“– ⚠️
Gregor Martynus
Gregor Martynus

πŸ’» ⚠️ πŸ›
Sam Mesterton-Gibbons
Sam Mesterton-Gibbons

πŸ’» πŸ› ⚠️
Rendall
Rendall

πŸ’» πŸ› ⚠️
Robert Massaioli
Robert Massaioli

πŸ’» πŸ›
Jan Kuča
Jan Kuča

πŸ’» ⚠️
Thomas Valadez
Thomas Valadez

πŸ“–
Asitha de Silva
Asitha de Silva

πŸ’» πŸ›
Mikhail Yermolayev
Mikhail Yermolayev

πŸ›
Alex Batalov
Alex Batalov

πŸ’» ⚠️
Federico Bevione
Federico Bevione

πŸ› πŸ’» ⚠️
Daisuke Yamamoto
Daisuke Yamamoto

πŸ’» πŸ› ⚠️
dnalborczyk
dnalborczyk

πŸ“– πŸ’» ⚠️
FabioWanner
FabioWanner

πŸ› πŸ’» ⚠️
Ash Smith
Ash Smith

πŸ’» πŸ› ⚠️
Micah Halter
Micah Halter

πŸ’» ⚠️ πŸ›
Yuto Yoshihara
Yuto Yoshihara

πŸ’» πŸ› ⚠️
Dakshraj Sharma
Dakshraj Sharma

πŸ’»
Shaosu Liu
Shaosu Liu

πŸ’»
Vytenis
Vytenis

πŸ’»
Eric Zorn
Eric Zorn

πŸ’» ⚠️ πŸ“–
Max Belsky
Max Belsky

πŸ’» πŸ›
Peter Bech
Peter Bech

πŸ’» πŸ›
Rusty Conover
Rusty Conover

πŸ’»
Dave Carlson
Dave Carlson

πŸ’»
ottomated
ottomated

πŸ’» πŸ›
Artem Shuvaev
Artem Shuvaev

πŸ’» πŸ›
ajaishankar
ajaishankar

πŸ“–
Dominik Dosoudil
Dominik Dosoudil

πŸ’» ⚠️
tkr
tkr

πŸ’» πŸ“–
berzi
berzi

πŸ’» πŸ“– ⚠️
Philip Trauner
Philip Trauner

πŸ’» πŸ“– ⚠️
Pavel Yermolin
Pavel Yermolin

πŸ’» πŸ“– ⚠️
Duncan Beevers
Duncan Beevers

πŸ’» πŸ› ⚠️
Timofey Kukushkin
Timofey Kukushkin

πŸ’» ⚠️ πŸ›
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!