What is openapi-typescript?
The openapi-typescript npm package is a tool that generates TypeScript types from OpenAPI specifications. This helps developers ensure type safety and better integration between their API definitions and TypeScript code.
What are openapi-typescript's main functionalities?
Generate TypeScript Types
This feature allows you to generate TypeScript types from an OpenAPI specification URL. The generated types are then saved to a file named 'types.ts'.
const openapiTS = require('openapi-typescript');
const fs = require('fs');
async function generateTypes() {
const types = await openapiTS('https://api.example.com/openapi.json');
fs.writeFileSync('types.ts', types);
}
generateTypes();
Generate Types from Local File
This feature allows you to generate TypeScript types from a local OpenAPI specification file. The generated types are saved to a file named 'types.ts'.
const openapiTS = require('openapi-typescript');
const fs = require('fs');
const path = require('path');
async function generateTypes() {
const types = await openapiTS(path.join(__dirname, 'openapi.json'));
fs.writeFileSync('types.ts', types);
}
generateTypes();
Custom Type Generation Options
This feature allows you to customize the type generation process by providing options such as a transform function. The transform function can be used to modify the schema before generating the types.
const openapiTS = require('openapi-typescript');
const fs = require('fs');
async function generateTypes() {
const types = await openapiTS('https://api.example.com/openapi.json', {
transform: (schema) => {
// Custom transformation logic
return schema;
}
});
fs.writeFileSync('types.ts', types);
}
generateTypes();
Other packages similar to openapi-typescript
swagger-typescript-api
The swagger-typescript-api package generates TypeScript API client code from Swagger/OpenAPI definitions. It provides more advanced features like generating API client methods and supports both Swagger 2.0 and OpenAPI 3.0 specifications.
typescript-fetch
The typescript-fetch package is a generator for TypeScript clients using the Fetch API. It generates TypeScript code from OpenAPI specifications and is particularly useful for creating client-side code that interacts with RESTful APIs.
openapi-typescript turns OpenAPI 3.0 & 3.1 schemas into TypeScript quickly using Node.js. No Java/node-gyp/running OpenAPI servers necessary.
The code is MIT-licensed and free for use.
Tip:
New to OpenAPI? Speakeasy’s Intro to OpenAPI is an accessible guide to newcomers that explains the “why” and “how” of OpenAPI.
Features
- ✅ Supports OpenAPI 3.0 and 3.1 (including advanced features like discriminators)
- ✅ Generate runtime-free types that outperform old school codegen
- ✅ Load schemas from YAML or JSON, locally or remotely
- ✅ Generate types for even huge schemas within milliseconds
Note: OpenAPI 2.x is supported with versions 5.x
and previous
Examples
👀 See examples
Setup
This library requires the latest version of Node.js installed (20.x or higher recommended). With that present, run the following in your project:
npm i -D openapi-typescript typescript
And in your tsconfig.json
, to load the types properly:
{
"compilerOptions": {
+ "module": "ESNext", // or "NodeNext"
+ "moduleResolution": "Bundler" // or "NodeNext"
}
}
Highly recommended
Also adding the following can boost type safety:
{
"compilerOptions": {
+ "noUncheckedIndexedAccess": true
}
}
Basic usage
First, generate a local type file by running npx openapi-typescript
, first specifying your input schema (JSON or YAML), and where you’d like the --output
(-o
) to be saved:
npx openapi-typescript ./path/to/my/schema.yaml -o ./path/to/my/schema.d.ts
npx openapi-typescript https://myapi.dev/api/v1/openapi.yaml -o ./path/to/my/schema.d.ts
Then in your TypeScript project, import types where needed:
import type { paths, components } from "./my-openapi-3-schema";
type MyType = components["schemas"]["MyType"];
type EndpointParams = paths["/my/endpoint"]["parameters"];
type SuccessResponse =
paths["/my/endpoint"]["get"]["responses"][200]["content"]["application/json"]["schema"];
type ErrorResponse =
paths["/my/endpoint"]["get"]["responses"][500]["content"]["application/json"]["schema"];
From here, you can use these types for any of the following (but not limited to):
- Using an OpenAPI-supported fetch client (like openapi-fetch)
- Asserting types for other API requestBodies and responses
- Building core business logic based on API types
- Validating mock test data is up-to-date with the current schema
- Packaging API types into any npm packages you publish (such as client SDKs, etc.)
📓 Docs
View Docs