{"id":16500257,"url":"https://github.com/toomuchdesign/openapi-ts-json-schema","last_synced_at":"2026-03-05T23:04:44.552Z","repository":{"id":182103136,"uuid":"666156985","full_name":"toomuchdesign/openapi-ts-json-schema","owner":"toomuchdesign","description":"OpenAPI ➡️ TypeScript JSON Schema generator.","archived":false,"fork":false,"pushed_at":"2024-04-13T18:00:34.000Z","size":884,"stargazers_count":11,"open_issues_count":2,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-04-14T02:24:03.804Z","etag":null,"topics":["generator","json-schema","openapi","swagger","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/toomuchdesign.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2023-07-13T21:07:28.000Z","updated_at":"2024-04-15T08:47:09.598Z","dependencies_parsed_at":"2024-04-15T08:57:35.405Z","dependency_job_id":null,"html_url":"https://github.com/toomuchdesign/openapi-ts-json-schema","commit_stats":null,"previous_names":["toomuchdesign/openapi-ts-json-schema"],"tags_count":12,"template":false,"template_full_name":"toomuchdesign/npm-package-template","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/toomuchdesign%2Fopenapi-ts-json-schema","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/toomuchdesign%2Fopenapi-ts-json-schema/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/toomuchdesign%2Fopenapi-ts-json-schema/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/toomuchdesign%2Fopenapi-ts-json-schema/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/toomuchdesign","download_url":"https://codeload.github.com/toomuchdesign/openapi-ts-json-schema/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":227440161,"owners_count":17776651,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["generator","json-schema","openapi","swagger","typescript"],"created_at":"2024-10-11T14:56:35.712Z","updated_at":"2026-03-05T23:04:44.547Z","avatar_url":"https://github.com/toomuchdesign.png","language":"TypeScript","readme":"# openapi-ts-json-schema\n\n[![Build Status][ci-badge]][ci]\n[![Npm version][npm-version-badge]][npm]\n[![Coveralls][coveralls-badge]][coveralls]\n\nGenerate **TypeScript-first JSON Schemas** (`.ts` modules with `as const`) directly from your OpenAPI definitions — so you can use the same schema for both **runtime validation** and **TypeScript type inference**.\n\n## Why?\n\nKeeping **OpenAPI specs**, **runtime validators**, and **TypeScript types** in sync is hard.\n\nMany teams end up maintaining the same api models in different formats:\n\n- JSON Schema for runtime validation (`Ajv`, `Fastify`, etc.)\n- TypeScript types for static checking\n\n`openapi-ts-json-schema` solves this by generating **TypeScript JSON Schemas directly from your OpenAPI definitions**: valid JSON schemas written as **TypeScript modules**, ready for runtime validation and type inference.\n\nThese schemas:\n\n- ✅ are 100% JSON Schema–compatible (usable with `Ajv`, `Fastify`, etc.)\n- ✅ are TypeScript-native (`as const` objects you can import)\n- ✅ can be used for type inference via [json-schema-to-ts](https://github.com/ThomasAribart/json-schema-to-ts)\n- ✅ are generated automatically from your OpenAPI spec\n\nIn short: **OpenAPI spec becomes the single source of truth** for both runtime validation and TypeScript typing.\n\n## Example\n\nFrom this OpenAPI definition:\n\n```yaml\ncomponents:\n  schemas:\n    User:\n      type: object\n      properties:\n        id: { type: string }\n        name: { type: string }\n      required: [id, name]\n```\n\nYou get this TypeScript JSON schema:\n\n```ts\n// components/schemas/User.ts\nexport default {\n  type: 'object',\n  properties: {\n    id: { type: 'string' },\n    name: { type: 'string' },\n  },\n  required: ['id', 'name'],\n} as const;\n```\n\nNow you can use it for both runtime validation and type inference:\n\n```ts\nimport Ajv from 'ajv';\nimport type { FromSchema } from 'json-schema-to-ts';\n\nimport userSchema from './components/schemas/User';\n\nconst ajv = new Ajv();\nconst validate = ajv.compile\u003cFromSchema\u003ctypeof userSchema\u003e\u003e(userSchema);\n\nconst data: unknown = {};\nif (validate(data)) {\n  // data is now typed as { id: string; name: string }\n} else {\n  console.error(validate.errors);\n}\n```\n\n## Installation\n\n```\nnpm i openapi-ts-json-schema -D\n```\n\n## Usage\n\n```ts\nimport { openapiToTsJsonSchema } from 'openapi-ts-json-schema';\n\nconst { outputPath } = await openapiToTsJsonSchema({\n  openApiDocument: 'path/to/open-api-specs.yaml',\n  targets: {\n    collections: ['components.schemas', 'paths'],\n  },\n});\n```\n\nSchemas are generated in a folder mirroring your OpenAPI layout (default: `schemas-autogenerated`).\n\n### CommonJS\n\nSince `openapi-ts-json-schema` is distributed as an ESM-only package, it must be imported using a dynamic `import()` when used from a CommonJS project:\n\n```ts\nasync function run() {\n  const { openapiToTsJsonSchema } = await import('openapi-ts-json-schema');\n\n  const { outputPath } = await openapiToTsJsonSchema({\n    openApiDocument: 'path/to/open-api-specs.yaml',\n    targets: {\n      collections: ['components.schemas', 'paths'],\n    },\n    moduleSystem: 'cjs',\n  });\n}\n\nrun();\n```\n\n## Options\n\n### Core options\n\n| Property                         | Type\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp; | Description                                                                                                                                                                                                                                                                                                                  | Default    |\n| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |\n| **openApiDocument** _(required)_ | `string`                                                                                                                                                                                                                                                                           | Path to an OpenAPI document (JSON or YAML).                                                                                                                                                                                                                                                                                  | -          |\n| **targets** _(required)_         | `{`\u003c/br\u003e` collections?: string[];`\u003c/br\u003e` single?: string[];`\u003c/br\u003e`}`                                                                                                                                                                                                               | OpenAPI definition paths to generate JSON Schemas from _(dot notation)_.\u003cbr/\u003e\u003cbr/\u003e`collections`: paths pointing to objects/records of definitions, where each entry will be generated (eg: `[\"components.schemas\"]`).\u003cbr/\u003e\u003cbr/\u003e`single`: paths pointing to individual definitions to generate (eg: `[\"paths./users/{id}\"]`). | -          |\n| **outputPath**                   | `string`                                                                                                                                                                                                                                                                           | Directory where generated schemas will be written. Defaults to `/schemas-autogenerated` in the same directory of `openApiDocument`.                                                                                                                                                                                          | -          |\n| **refHandling**                  | `\"import\" \\| \"inline\" \\| \"keep\"`                                                                                                                                                                                                                                                   | `\"import\"`: generate and import `$ref` schemas.\u003cbr/\u003e`\"inline\"`: inline `$ref` schemas.\u003cbr/\u003e`\"keep\"`: keep `$ref` values.                                                                                                                                                                                                     | `\"import\"` |\n| **moduleSystem**                 | `\"cjs\" \\| \"esm\"`                                                                                                                                                                                                                                                                   | Controls how import specifiers are written in generated artifacts. Configure this option based on whether the consuming project is using CommonJS or ECMAScript modules.                                                                                                                                                     | `\"esm\"`    |\n| **silent**                       | `boolean`                                                                                                                                                                                                                                                                          | Don't log user messages.                                                                                                                                                                                                                                                                                                     | `false`    |\n\n### Advanced options\n\n| Property          | Type                                       | Description                                                                                           | Default |\n| ----------------- | ------------------------------------------ | ----------------------------------------------------------------------------------------------------- | ------- |\n| **idMapper**      | `(params: { id: string }) =\u003e string`       | Customize generated schemas `$id`s and `$ref`s values. Useful for enforcing naming conventions.       | -       |\n| **schemaPatcher** | `(params: { schema: JSONSchema }) =\u003e void` | Hook called for every generated schema node, allowing programmatic mutation before output.            | -       |\n| **plugins**       | `ReturnType\u003cPlugin\u003e[]`                     | List of plugins to extend or customize the generation process. See [plugins docs](./docs/plugins.md). | -       |\n\n### Full configuration example\n\n```ts\nimport {\n  generateSchemaWith,\n  openapiToTsJsonSchema,\n} from 'openapi-ts-json-schema';\n\nawait openapiToTsJsonSchema({\n  openApiDocument: './openapi.yaml',\n  targets: {\n    collections: ['components.schemas'],\n    single: ['paths./users/{id}'],\n  },\n  outputPath: './generated',\n  refHandling: 'import',\n  moduleSystem: 'esm',\n  silent: false,\n\n  idMapper: ({ id }) =\u003e id.toUpperCase(),\n  schemaPatcher: ({ schema }) =\u003e {\n    if (schema.properties \u0026\u0026 !schema.type) {\n      schema.type = 'object';\n    }\n  },\n  plugins: [generateSchemaWith$idPlugin()],\n});\n```\n\n### `refHandling` option\n\nThree strategies for how `$ref`s are resolved:\n\n| `refHandling` option | description                                                                                    |\n| -------------------- | ---------------------------------------------------------------------------------------------- |\n| `inline`             | Inlines `$refs`s, creating self-contained schemas (no imports, but possible redundancy).       |\n| `import`             | Replaces`$ref`s with imports of the target definition                                          |\n| `keep`               | Leaves `$ref`s untouched — useful if you plan to interpret `$ref`s dynamically or use a plugin |\n\nCircular references are supported:\n\n- `inline`: circular refs are replaced with `{}`\n- `import`: resolves the JSON schema but TypeScript recursion halts (`any` type, TS error 7022)\n- `keep`: circular refs left unresolved\n\nSee [tests](https://github.com/toomuchdesign/openapi-ts-json-schema/blob/master/test/circularReference.test.ts) for details.\n\n## Return values\n\nAlong with generated schema files, `openapi-ts-json-schema` returns metadata:\n\n```ts\n{\n  // The path where the schemas are generated\n  outputPath: string;\n  metaData: {\n    // Meta data of the generated schemas\n    schemas: Map\u003c\n      // Schema internal id. Eg: \"/components/schemas/MySchema\"\n      string,\n      {\n        id: string;\n        // Internal unique schema identifier. Eg `\"/components/schemas/MySchema\"`\n        $id: string;\n        // JSON schema Compound Schema Document `$id`. Eg: `\"/components/schemas/MySchema\"`\n        uniqueName: string;\n        // Unique JavaScript identifier used as import name. Eg: `\"componentsSchemasMySchema\"`\n        openApiDefinition: OpenApiObject;\n        // Original dereferenced openAPI definition\n        originalSchema: JSONSchema | string;\n        // Original dereferenced JSON schema\n        isRef: boolean;\n        // True if schemas is used as a `$ref`\n        shouldBeGenerated: boolean;\n        // Text content of schema file\n        fileContent?: string;\n\n        absoluteDirName: string;\n        // Absolute path pointing to schema folder (posix or win32). Eg: `\"Users/username/output/path/components/schemas\"`\n        absolutePath: string;\n        // Absolute path pointing to schema file (posix or win32). Eg: `\"Users/username/output/path/components/schemas/MySchema.ts\"`\n        absoluteImportPath: string;\n        // Absolute import path (posix or win32, without extension). Eg: `\"Users/username/output/path/components/schemas/MySchema\"`\n      }\n    \u003e;\n  }\n}\n```\n\n## Plugins\n\nExtend `openapi-ts-json-schema` with custom generators. Currently available plugins:\n\n- `generateSchemaWith$idPlugin`\n- `fastifyIntegrationPlugin`\n\nSee [plugins documentation 📖](./docs/plugins.md).\n\n## How it works\n\nGiven an OpenAPI definition file, `openapi-ts-json-schema`:\n\n- Resolves and dereferences $refs (using [@apidevtools/json-schema-ref-parser](https://github.com/APIDevTools/json-schema-ref-parser))\n- Converts OpenAPI objects to JSON Schema (via [@openapi-contrib/openapi-schema-to-json-schema](https://github.com/APIDevTools/json-schema-ref-parser) \u0026 [`openapi-jsonschema-parameters`](https://www.npmjs.com/package/openapi-jsonschema-parameters))\n- Generates `.ts` files exporting each schema as `as const`\n- Mirrors the original OpenAPI structure in the generated folder\n- Supports plugins (e.g. for Fastify integration)\n\nTake a look at the [Developer's notes](./docs/developer-notes.md) for a few more in-depth explanations.\n\n## Todo\n\n- Improve external `#ref`s handling (currently being inlined and duplicated)\n- Find a way to merge multiple different OpenApi definitions consistently\n- Consider implementing an option to inline circular `$ref`s with a configurable nesting level\n\n[ci-badge]: https://github.com/toomuchdesign/openapi-ts-json-schema/actions/workflows/ci.yml/badge.svg\n[ci]: https://github.com/toomuchdesign/openapi-ts-json-schema/actions/workflows/ci.yml\n[coveralls-badge]: https://coveralls.io/repos/github/toomuchdesign/openapi-ts-json-schema/badge.svg?branch=master\n[coveralls]: https://coveralls.io/github/toomuchdesign/openapi-ts-json-schema?branch=master\n[npm]: https://www.npmjs.com/package/openapi-ts-json-schema\n[npm-version-badge]: https://img.shields.io/npm/v/openapi-ts-json-schema.svg\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftoomuchdesign%2Fopenapi-ts-json-schema","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftoomuchdesign%2Fopenapi-ts-json-schema","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftoomuchdesign%2Fopenapi-ts-json-schema/lists"}