{"id":14986703,"url":"https://github.com/ts-oas/ts-oas","last_synced_at":"2025-04-11T20:31:46.187Z","repository":{"id":62463021,"uuid":"559674094","full_name":"ts-oas/ts-oas","owner":"ts-oas","description":"Automatically generate OpenAPI specifications from Typescript types.","archived":false,"fork":false,"pushed_at":"2025-03-04T19:13:21.000Z","size":131,"stargazers_count":18,"open_issues_count":1,"forks_count":4,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-25T18:15:24.401Z","etag":null,"topics":["json-schema","oas","openapi","openapi-generator","openapi3","openapi31","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/ts-oas.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","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,"publiccode":null,"codemeta":null}},"created_at":"2022-10-30T20:36:46.000Z","updated_at":"2025-03-18T20:04:49.000Z","dependencies_parsed_at":"2024-06-08T21:21:52.818Z","dependency_job_id":"bce98881-a75d-48e4-813f-742c892f79ca","html_url":"https://github.com/ts-oas/ts-oas","commit_stats":{"total_commits":37,"total_committers":5,"mean_commits":7.4,"dds":"0.21621621621621623","last_synced_commit":"f1a95604e960d9913066e56b211e2c552fc7ef21"},"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ts-oas%2Fts-oas","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ts-oas%2Fts-oas/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ts-oas%2Fts-oas/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ts-oas%2Fts-oas/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ts-oas","download_url":"https://codeload.github.com/ts-oas/ts-oas/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248476327,"owners_count":21110257,"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":["json-schema","oas","openapi","openapi-generator","openapi3","openapi31","swagger","typescript"],"created_at":"2024-09-24T14:13:22.886Z","updated_at":"2025-04-11T20:31:41.131Z","avatar_url":"https://github.com/ts-oas.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Typescript OpenAPI Spec Generator\n\n[![NPM version](https://img.shields.io/npm/v/ts-oas.svg)](https://www.npmjs.com/package/ts-oas)\n![GitHub License](https://img.shields.io/github/license/ts-oas/ts-oas)\n![NPM Unpacked Size](https://img.shields.io/npm/unpacked-size/ts-oas)\n\n\nAutomatically generate OpenAPI (formerly Swagger) specifications from Typescript types. Supports OpenAPI **v3.1** and **v3.0**. Requires interfaces/types in a specific format.\n\n## Benefits\n\n-   **Write once, use many.** Typescript provides a fluent way to declare API specifications. With `ts-oas`, you can use the generated specs not only for documentation but also for input validation (eg. with AJV), serialization, maintaining business logic or test codes (with generics), and more.\n-   **Automation first.** Simply write a script to regenerate specs accordingly after any type changes.\n-   **Headless.** Works seamlessly with any server-side framework, unlike some other tools.\n\n## Features\n\n-   Both [Programmatic](#a-quick-example) and [Command line](#cli) support.\n-   Reference schemas and components. Generate schema references that correspond to their Typescript type references.\n-   Supports JSDoc annotations. With both pre-defined and custom keywords, metadata can be included in every schema object.\n-   Schema processor function for any custom post-processing (if JSDoc annotations aren't enough).\n-   Generate schemas separately.\n-   Typescript 4 and 5 compliant.\n\n## Install\n\n```\nnpm i ts-oas\n```\n\n## Getting Started\n\nFirstly, We need types for each API, compatible with the following format:\n\n```ts\ntype Api = {\n    path: string;\n    method: HTTPMethod;\n    body?: Record\u003cstring, any\u003e;\n    params?: Record\u003cstring, any\u003e;\n    query?: Record\u003cstring, any\u003e;\n    responses: Partial\u003cRecord\u003cHttpStatusCode, any\u003e\u003e;\n    security?: Record\u003cstring, string[]\u003e[];\n};\n```\n\n### A quick example\n\nWe have `interfaces.ts` where our API types are present:\n\n```ts\nimport { ApiMapper } from \"ts-oas\"; // Recommended to use ApiMapper to help to keep the format valid.\n\nexport type GetBarAPI = ApiMapper\u003c{\n    path: \"/foo/bar/:id\";\n    method: \"GET\";\n    params: {\n        id: number;\n    };\n    query: {\n        from_date: Date;\n    };\n    responses: {\n        /**\n         * @contentType application/json\n         */\n        \"200\": Bar;\n        \"404\": { success: false };\n    };\n}\u003e;\n\n/**\n * Sample description.\n * @summary Add a Bar\n */\nexport type AddBarAPI = ApiMapper\u003c{\n    path: \"/foo/bar\";\n    method: \"POST\";\n    body: Bar;\n    responses: {\n        /**\n         * No content\n         */\n        \"201\": never;\n    };\n}\u003e;\n\nexport type Bar = {\n    /**\n     * Description for barName.\n     * @minLength 10\n     */\n    barName: string;\n    barType: \"one\" | \"two\";\n};\n```\n\nIn `script.ts` file:\n\n```ts\nimport TypescriptOAS, { createProgram } from \"ts-oas\";\nimport { resolve } from \"path\";\n\n// create a Typescript program. or any generic ts program can be used.\nconst tsProgram = createProgram([\"interfaces.ts\"], { strictNullChecks: true }, resolve());\n\n// initiate the OAS generator.\nconst tsoas = new TypescriptOAS(tsProgram, { ref: true });\n\n// get the complete OAS. determine type names (Regex/exact name) to be considered for specs.\nconst specObject = tsoas.getOpenApiSpec([/API$/]); // all types that ends with \"API\"\n\n// log results:\nconsole.log(JSON.stringify(specObject, null, 4));\n\n// or write into a ts file:\n// writeFileSync(\"./schema.ts\", `const spec = ${inspect(specObject, { depth: null })};\\n`);\n```\n\nRun the above script.\n\n\u003cdetails\u003e\u003csummary\u003eExpected output\u003c/summary\u003e\n\n```json\n{\n    \"openapi\": \"3.1.0\",\n    \"info\": {\n        \"title\": \"OpenAPI specification\",\n        \"version\": \"1.0.0\"\n    },\n    \"components\": {\n        \"schemas\": {\n            \"Bar\": {\n                \"type\": \"object\",\n                \"properties\": {\n                    \"barName\": {\n                        \"description\": \"Description for barName.\",\n                        \"minLength\": 10,\n                        \"type\": \"string\"\n                    },\n                    \"barType\": {\n                        \"enum\": [\"one\", \"two\"],\n                        \"type\": \"string\"\n                    }\n                },\n                \"required\": [\"barName\", \"barType\"]\n            }\n        }\n    },\n    \"paths\": {\n        \"/foo/bar/:id\": {\n            \"get\": {\n                \"operationId\": \"GetBarAPI\",\n                \"parameters\": [\n                    {\n                        \"name\": \"id\",\n                        \"in\": \"path\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"number\"\n                        }\n                    },\n                    {\n                        \"name\": \"from_date\",\n                        \"in\": \"query\",\n                        \"required\": true,\n                        \"schema\": {\n                            \"type\": \"string\",\n                            \"format\": \"date-time\"\n                        }\n                    }\n                ],\n                \"responses\": {\n                    \"200\": {\n                        \"description\": \"\",\n                        \"content\": {\n                            \"application/json\": {\n                                \"schema\": {\n                                    \"$ref\": \"#/components/schemas/Bar\"\n                                }\n                            }\n                        }\n                    },\n                    \"404\": {\n                        \"description\": \"\",\n                        \"content\": {\n                            \"*/*\": {\n                                \"schema\": {\n                                    \"type\": \"object\",\n                                    \"properties\": {\n                                        \"success\": {\n                                            \"type\": \"boolean\",\n                                            \"enum\": [false]\n                                        }\n                                    },\n                                    \"required\": [\"success\"]\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        },\n        \"/foo/bar\": {\n            \"post\": {\n                \"operationId\": \"AddBarAPI\",\n                \"description\": \"Sample description.\",\n                \"summary\": \"Add a Bar\",\n                \"requestBody\": {\n                    \"content\": {\n                        \"*/*\": {\n                            \"schema\": {\n                                \"$ref\": \"#/components/schemas/Bar\"\n                            }\n                        }\n                    }\n                },\n                \"responses\": {\n                    \"201\": {\n                        \"description\": \"No content\"\n                    }\n                }\n            }\n        }\n    }\n}\n```\n\n\u003c/details\u003e\n\n### Get schemas separately\n\nSchemas with any format can be generated by:\n\n```ts\nconst schema = tsoas.getSchemas([\"Bar\"]);\nconsole.log(schema);\n```\n\n\u003cdetails\u003e\u003csummary\u003eExpected output\u003c/summary\u003e\n\n```\n{\n  Bar: {\n    type: 'object',\n    properties: {\n      barName: {\n        description: 'Description for barName.',\n        minLength: 10,\n        type: 'string'\n      },\n      barType: { enum: [ 'one', 'two' ], type: 'string' }\n    },\n    required: [ 'barName', 'barType' ]\n  }\n}\n```\n\n\u003c/details\u003e\n\n## CLI\n\nCommand line tool is designed to behave just like the programmatic way. Once it has been installed, CLI can be executed using `npx ts-oas`, or just `ts-oas` if installed globally.\n\n```\nUsage: ts-oas \u003cfile-paths\u003e \u003ctype-names\u003e [options]\n\n\u003cfile-paths\u003e : Comma-separated list of relative .ts file paths which contain\ntypes.\n\u003ctype-names\u003e : Comma-separated list of type names (Regex/exact name) to be\nconsidered in files.\n\nOptions:\n  -c, --tsconfig-file  Path to a JSON tsconfig file.                    [string]\n  -p, --options-file   Path to a JSON file containing 'ts-oas' Options. Refer to\n                       the documentation.                               [string]\n  -s, --spec-file      Path to a JSON file containing additional OpenAPI\n                       specifications.                                  [string]\n  -e, --schema-only    Only generates pure schemas from given types.\n                       ('spec-file' will be ignored.)                  [boolean]\n  -o, --output         Path to a JSON file that will be used to write the\n                       output. Will create the file if not existed.     [string]\n  -h, --help           Show help                                       [boolean]\n  -v, --version        Show version number                             [boolean]\n\nExamples:\n  ts-oas ./interfaces/sample.ts myApi,mySecondApi\n\n```\n\n## Documentations\n\n### JSDoc annotations\n\n| Keyword                                                        | Fields  | Examples                                                                                                     |\n| -------------------------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------ |\n| @default                                                       | any     | `@default foo` `@default 3` `@default [\"a\", \"b\", \"c\"]`                                                       |\n| @format                                                        | strings | `@format email`                                                                                              |\n| @items                                                         | arrays  | `@items.minimum 1` `@items.format email` `@items {\"type\":\"integer\", \"minimum\":0}` `@default [\"a\", \"b\", \"c\"]` |\n| @$ref                                                          | any     | `@ref http://my-schema.org`                                                                                  |\n| @title                                                         | any     | `@title foo`                                                                                                 |\n| @minimum\u003cbr\u003e@maximum\u003cbr\u003e@exclusiveMinimum\u003cbr\u003e@exclusiveMaximum | numbers | `@minimum 10` `@maximum 100`                                                                                 |\n| @minLength\u003cbr\u003e@maxLength                                       | strings | `@minLength 10` `@maxLength 100`                                                                             |\n| @minItems\u003cbr\u003e@maxItems                                         | arrays  | `@minItems 10` `@maxItems 100`                                                                               |\n| @minProperties\u003cbr\u003e@maxProperties                               | objects | `@minProperties 10` `@maxProperties 100`                                                                     |\n| @additionalProperties                                          | objects | `@additionalProperties`                                                                                      |\n| @ignore                                                        | any     | `@ignore`                                                                                                    |\n| @pattern                                                       | strings | `@pattern /^[0-9a-z]+$/g`                                                                                    |\n| @example                                                       | any     | `@example foo` `@example {\"abc\":true}` `@example require('./examples.ts').myExampleConst`                    |\n| @examples                                                      | any     | `@example [\"foo\", \"bar\"]` `@example require('./examples.ts').myExampleArrayConst`                            |\n\n#### Special keywords for root of API types\n\n| @summary | @operationId | @tags | @ignore | @body.description | @body.contentType |\n| -------- | ------------ | ----- | ------- | ----------------- | ----------------- |\n\n\u003cdetails\u003e\u003csummary\u003eExample\u003c/summary\u003e\n\n```ts\n/**\n * Sample description.\n * @summary Summary of Endpoint\n * @operationId addBar\n * @tags foos,bars\n * @ignore\n * @body.description Description for body of request.\n * @body.contentType application/json\n */\nexport type AddBarAPI = ApiMapper\u003c{\n    path: \"/foo/bar\";\n    method: \"POST\";\n    body: Bar;\n    responses: {\n        \"201\": {};\n    };\n}\u003e;\n```\n\n\u003c/details\u003e\n\n#### Special keywords for response items\n\n| @contentType |\n| ------------ |\n\n\u003cdetails\u003e\u003csummary\u003eExample\u003c/summary\u003e\n\n```ts\n    ...\n    responses: {\n        /**\n        * Description for response 200.\n        * @contentType application/json\n        */\n        \"200\": { success: true };\n    };\n```\n\n\u003c/details\u003e\n\n### Options\n\n#### `ref`\n\n\u003e _default: false_\n\nDefines references for schemas  based on their type references.\n\n#### `titles`\n\n\u003e _default: false_\n\nProvides a `title` field in each schema, filled with its corresponding field name or type name.\n\n#### `ignoreRequired`\n\n\u003e _default: false_\n\nIgnores the `required` field in all schemas.\n\n#### `ignoreErrors`\n\n\u003e _default: false_\n\nIgnores errors in Typescript files. May introduce wrong schemas.\n\n#### `uniqueNames`\n\n\u003e _default: false_\n\nReplaces every type name with a unique hash to avoid duplication issues.\n\n#### `tsNodeRegister`\n\n\u003e _default: false_\n\nUses `ts-node/register` as a runtime argument, enabling direct execution of TypeScript on Node.js without precompiling.\n\n#### `nullableKeyword`\n\n\u003e _default: true_\n\nProvides `nullable: true` for nullable fields; otherwise, set `type: \"null\"`.\n\n#### `defaultContentType`\n\n\u003e _default: \"\\*/\\*\"_\n\nSets the default content type for all operations. This can be overridden case-by-case (see the annotations section).\n\n#### `defaultNumberType`\n\n\u003e _default: \"number\"_\n\nSets the default schema type for number values, which can be overridden case-by-case (see the annotations section).\n\n#### `customKeywords`\n\nA list of custom keywords to consider in annotations.\n\n#### `customKeywordPrefix`\n\n\u003e _default: \"x-\"_\n\nThe prefix added to all `customKeywords`.\n\n#### `schemaProcessor`\n\nA function that runs over each generated schema.\n\n## Inspirations\n\n`ts-oas` is highly inspired by [typescript-json-schema](https://github.com/YousefED/typescript-json-schema). While using the so-called library, it took lots of workarounds to create compatible OpenAPI v3.0 specs. For example, modifying output schemas enforced us to use schema-walker tools which added lots of overhead in our scripts (Despite of compatible OpenAPI schemas in `ts-oas`, we added a schema-processor custom function as an option as well).\n\n\n## Contributing\n\nContributions of any kind are welcome!\n\n\u003cdetails\u003e\u003csummary\u003eTODOs\u003c/summary\u003e\n\n-   [x] CLI\n-   [ ] Support for request and response header specs\n-   [ ] More docs and examples\n-   [ ] Complete tests\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fts-oas%2Fts-oas","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fts-oas%2Fts-oas","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fts-oas%2Fts-oas/lists"}