Top 10 OpenAPI TypeScript Features Explained
Looking for a Postman alternative?
Try APIDog, the Most Customizable Postman Alternative, where you can connect to thousands of APIs right now!
Introduction
The OpenAPI specification is a widely adopted standard for designing, building, and documenting APIs. It provides a set of rules and guidelines for defining the structure, endpoints, parameters, and responses of an API. With an OpenAPI specification, developers can easily understand and interact with APIs, making it an essential tool for API development.
However, one of the challenges developers face is generating TypeScript JSON schemas from an OpenAPI specification. TypeScript JSON schemas provide a way to define the data types and structures used in a TypeScript application. They ensure type safety and provide a convenient way to validate data before it is passed into API endpoints or consumed by client applications.
In my experience, there are existing libraries that can generate JSON schema files from an OpenAPI specification. However, there was no clear way to generate TypeScript JSON schemas using these libraries. This led me to develop my own solution called openapi-ts-json-schema, which fills this gap and provides a seamless way to generate TypeScript JSON schemas from an OpenAPI specification.
In this article, I will guide you through the process of generating TypeScript JSON schemas from an OpenAPI specification using the openapi-ts-json-schema package. We will cover the main steps involved and provide working sample code to illustrate each step.
Filling the Gap: OpenAPI Specification and TypeScript JSON Schema Format
When I first started working with OpenAPI specifications, I quickly realized the need for TypeScript JSON schemas that matched the structure defined in the specification. While there were libraries available to generate JSON schema files, they did not provide a clear way to generate TypeScript JSON schemas.
To address this gap, I developed the openapi-ts-json-schema package. This package leverages existing libraries and tools to automate the process of generating TypeScript JSON schemas from an OpenAPI specification. By using this package, developers can easily maintain type safety and consistency between their API specification and TypeScript codebase.
Step-by-Step Guide: Generating TypeScript JSON Schemas from OpenAPI Specification
Let’s dive into the step-by-step process of generating TypeScript JSON schemas from an OpenAPI specification using the openapi-ts-json-schema package.
1. Resolve External/Remote $refs and Dereference with @apidevtools/json-schema-ref-parser
The OpenAPI specification allows users to define reusable components and reference them using $ref pointers. These pointers can be either internal, referring to components within the same specification, or external, referring to components in separate files or remote locations.
To ensure that our TypeScript JSON schemas are complete and self-contained, we need to resolve and dereference these external/remote $refs. This can be achieved using the @apidevtools/json-schema-ref-parser
library.
Here’s a sample code snippet that demonstrates how to resolve external/remote $refs and dereference them using json-schema-ref-parser
:
import * as RefParser from '@apidevtools/json-schema-ref-parser';
import * as fs from 'fs';
const openapiSpecPath = './openapi-spec.yaml';
const outputDirectory = './output';
async function generateSchemasFromOpenAPI() {
const parser = new RefParser();
// Parse the OpenAPI specification
const apiSpec = await parser.bundle(openapiSpecPath);
// Dereference external/remote $refs
const dereferencedSpec = await parser.dereference(apiSpec);
// Write the dereferenced specification to a JSON file
fs.writeFileSync(`${outputDirectory}/dereferenced-spec.json`, JSON.stringify(dereferencedSpec, null, 2));
console.log('Dereferenced specification generated successfully.');
}
generateSchemasFromOpenAPI().catch(error => console.error(error));
2. Convert to JSON Schema with @openapi-contrib/openapi-schema-to-json-schema and openapi-jsonschema-parameters
Once we have a dereferenced OpenAPI specification, the next step is to convert it to JSON schema format. This ensures that our TypeScript JSON schemas are compatible with the JSON schema standard and can be easily used in TypeScript applications.
The @openapi-contrib/openapi-schema-to-json-schema
library provides the necessary tools to convert OpenAPI schemas to JSON schemas. Additionally, the openapi-jsonschema-parameters
library can be used to convert OpenAPI parameter definitions to JSON schemas.
Here’s a code snippet showing how to perform this conversion:
import { convert } from '@openapi-contrib/openapi-schema-to-json-schema';
import * as fs from 'fs';
const dereferencedSpecPath = './output/dereferenced-spec.json';
const outputDirectory = './output';
async function convertToJSONSchema() {
// Read the dereferenced specification from the JSON file
const dereferencedSpec = JSON.parse(fs.readFileSync(dereferencedSpecPath, 'utf8'));
// Convert OpenAPI schemas to JSON schemas
const jsonSchemas = convert(dereferencedSpec.components.schemas);
// Write the converted JSON schemas to separate files
for (const [definitionName, schema] of Object.entries(jsonSchemas)) {
fs.writeFileSync(`${outputDirectory}/${definitionName}.json`, JSON.stringify(schema, null, 2));
}
console.log('JSON schemas converted successfully.');
}
convertToJSONSchema().catch(error => console.error(error));
3. Generate TypeScript JSON Schema Files for Each Definition
In the previous step, we converted the OpenAPI schemas to JSON schemas. Now, we will generate separate TypeScript JSON schema files for each definition in the OpenAPI specification. This step ensures that we have individual files for each definition, making it easier to manage and import the TypeScript JSON schemas in our TypeScript codebase.
Here’s a code snippet that demonstrates how to generate TypeScript JSON schema files for each definition:
import * as fs from 'fs';
const jsonSchemasDirectory = './output';
const outputDirectory = './output/typings';
function generateTypeScriptSchemas() {
// Read the JSON schemas in the directory
const jsonSchemas = fs.readdirSync(jsonSchemasDirectory);
// Generate TypeScript JSON schema files for each definition
for (const jsonSchemaFile of jsonSchemas) {
const definitionName = jsonSchemaFile.slice(0, -5); // Remove the '.json' extension
const schemaPath = `${jsonSchemasDirectory}/${jsonSchemaFile}`;
const jsonSchema = JSON.parse(fs.readFileSync(schemaPath, 'utf8'));
// Generate the TypeScript JSON schema file
const typeScriptSchema = `export type ${definitionName} = ${JSON.stringify(jsonSchema, null, 2)};`;
fs.writeFileSync(`${outputDirectory}/${definitionName}.json`, typeScriptSchema);
}
console.log('TypeScript JSON schema files generated successfully.');
}
generateTypeScriptSchemas();
With these three steps, we can effectively generate TypeScript JSON schemas from an OpenAPI specification using the openapi-ts-json-schema package. The resulting TypeScript JSON schemas can be used to maintain type safety, validate data, and ensure consistency between the API specification and TypeScript codebase.
Conclusion
In this article, we explored the process of generating TypeScript JSON schemas from an OpenAPI specification using the openapi-ts-json-schema package. We covered the main steps involved, including resolving external/remote $refs, converting to JSON schema format, and generating individual TypeScript JSON schema files for each definition.
While the openapi-ts-json-schema package fills the gap between the OpenAPI specification and TypeScript JSON schema format, it is important to note that it may not cover every specific use case. Therefore, I encourage readers to explore the package, experiment with it, and start a discussion if it doesn’t fit their specific needs.
Lastly, I hope that TypeScript will add native support for importing JSON schemas and inferring types natively from any JSON schema. This would further simplify the process of integrating OpenAPI specifications with TypeScript codebases, providing a more seamless development experience.
Looking for a Postman alternative?
Try APIDog, the Most Customizable Postman Alternative, where you can connect to thousands of APIs right now!