{"id":13455055,"url":"https://github.com/astahmer/openapi-zod-client","last_synced_at":"2025-05-13T22:03:21.251Z","repository":{"id":57750110,"uuid":"523637502","full_name":"astahmer/openapi-zod-client","owner":"astahmer","description":"Generate a zodios (typescript http client with zod validation) from an OpenAPI spec (json/yaml)","archived":false,"fork":false,"pushed_at":"2025-02-10T16:46:16.000Z","size":1136,"stargazers_count":945,"open_issues_count":84,"forks_count":106,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-04-29T13:45:58.883Z","etag":null,"topics":["api","axios","cli","client","generator","openapi","swagger","typescript","zod","zodios"],"latest_commit_sha":null,"homepage":"openapi-zod-client.vercel.app","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/astahmer.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":null,"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-08-11T08:07:09.000Z","updated_at":"2025-04-29T10:55:21.000Z","dependencies_parsed_at":"2023-11-28T13:45:10.965Z","dependency_job_id":"fc3d701d-c59f-4c9a-80bc-3648fc3ef15e","html_url":"https://github.com/astahmer/openapi-zod-client","commit_stats":{"total_commits":588,"total_committers":47,"mean_commits":12.51063829787234,"dds":"0.44387755102040816","last_synced_commit":"76d86f66332a86742bed192689281f6da96d3305"},"previous_names":[],"tags_count":74,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/astahmer%2Fopenapi-zod-client","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/astahmer%2Fopenapi-zod-client/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/astahmer%2Fopenapi-zod-client/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/astahmer%2Fopenapi-zod-client/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/astahmer","download_url":"https://codeload.github.com/astahmer/openapi-zod-client/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254036811,"owners_count":22003653,"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":["api","axios","cli","client","generator","openapi","swagger","typescript","zod","zodios"],"created_at":"2024-07-31T08:01:00.752Z","updated_at":"2025-05-13T22:03:21.199Z","avatar_url":"https://github.com/astahmer.png","language":"TypeScript","readme":"[![npm version](https://img.shields.io/npm/v/openapi-zod-client.svg)](https://www.npmjs.com/package/openapi-zod-client)\n\n# openapi-zod-client\n\n[![Screenshot 2022-11-12 at 18 52 25](https://user-images.githubusercontent.com/47224540/201487856-ffc4c862-6f31-4de1-8ef1-3981fabf3416.png)](https://openapi-zod-client.vercel.app/)\n\nGenerates a [zodios](https://github.com/ecyrbe/zodios) (_typescript http client with zod validation_) from a (json/yaml) [OpenAPI spec](https://github.com/OAI/OpenAPI-Specification) **(or just use the generated schemas/endpoints/etc !)**\n\n-   can be used programmatically _(do w/e you want with the computed schemas/endpoints)_\n-   or used as a CLI _(generates a prettier .ts file with deduplicated variables when pointing to the same schema/$ref)_\n\n-   client typesafety and runtime validation using [zodios](https://github.com/ecyrbe/zodios)\n-   tested (using [vitest](https://vitest.dev/)) against official [OpenAPI specs samples](https://github.com/OAI/OpenAPI-Specification/tree/main/schemas)\n\n# Why this exists\n\nSometimes you don't have control on your API, maybe you need to consume APIs from other teams (who might each use a different language/framework), you only have their Open API spec as source of truth, then this might help 😇\n\nYou could use `openapi-zod-client` to automate the API integration part (doesn't matter if you consume it in your front or back-end, zodios is agnostic) on your CI and just import the generated `api` client\n\n## Comparison vs tRPC zodios ts-rest etc\n\nIf you do have control on your API/back-end, you should probably use a RPC-like solution like [tRPC](https://github.com/trpc/trpc), [zodios](https://www.zodios.org/) or [ts-rest](https://ts-rest.com/) instead of this.\n\n# Comparison vs typed-openapi\n\n-   `openapi-zod-client` is a CLI that generates a [zodios](https://www.zodios.org/) API client (typescript http client with zod validation), currently using axios as http client\n-   [`typed-openapi`](https://github.com/astahmer/typed-openapi) is a CLI/library that generates a headless (bring your own fetcher : fetch, axios, ky, etc...) Typescript API client from an OpenAPI spec, that can output schemas as either just TS types (providing instant suggestions in your IDE) or different runtime validation schemas (zod, typebox, arktype, valibot, io-ts, yup)\n\n# Usage\n\nwith local install:\n\n-   `pnpm i -D openapi-zod-client`\n-   `pnpm openapi-zod-client \"./input/file.json\" -o \"./output/client.ts\"`\n\nor directly (no install)\n\n-   `pnpx openapi-zod-client \"./input/file.yaml\" -o \"./output/client.ts\"`\n\n# auto-generated doc\n\nhttps://paka.dev/npm/openapi-zod-client\n\n## CLI\n\n```sh\nopenapi-zod-client/1.15.0\n\nUsage:\n  $ openapi-zod-client \u003cinput\u003e\n\nCommands:\n  \u003cinput\u003e  path/url to OpenAPI/Swagger document as json/yaml\n\nFor more info, run any command with the `--help` flag:\n  $ openapi-zod-client --help\n\nOptions:\n  -o, --output \u003cpath\u003e               Output path for the zodios api client ts file (defaults to `\u003cinput\u003e.client.ts`)\n  -t, --template \u003cpath\u003e             Template path for the handlebars template that will be used to generate the output\n  -p, --prettier \u003cpath\u003e             Prettier config path that will be used to format the output client file\n  -b, --base-url \u003curl\u003e              Base url for the api\n  --no-with-alias                   With alias as api client methods (default: true)\n  -a, --with-alias                  With alias as api client methods (default: true)\n  --api-client-name \u003cname\u003e          when using the default `template.hbs`, allow customizing the `export const {apiClientName}`\n  --error-expr \u003cexpr\u003e               Pass an expression to determine if a response status is an error\n  --success-expr \u003cexpr\u003e             Pass an expression to determine which response status is the main success status\n  --media-type-expr \u003cexpr\u003e          Pass an expression to determine which response content should be allowed\n  --export-schemas                  When true, will export all `#/components/schemas`\n  --implicit-required               When true, will make all properties of an object required by default (rather than the current opposite), unless an explicitly `required` array is set\n  --with-deprecated                 when true, will keep deprecated endpoints in the api output\n  --with-description                when true, will add z.describe(xxx)\n  --with-docs                       when true, will add jsdoc comments to generated types \n  --group-strategy                  groups endpoints by a given strategy, possible values are: 'none' | 'tag' | 'method' | 'tag-file' | 'method-file'\n  --complexity-threshold            schema complexity threshold to determine which one (using less than `\u003c` operator) should be assigned to a variable\n  --default-status                  when defined as `auto-correct`, will automatically use `default` as fallback for `response` when no status code was declared\n  --all-readonly                    when true, all generated objects and arrays will be readonly\n  --export-types                    When true, will defined types for all object schemas in `#/components/schemas`\n  --additional-props-default-value  Set default value when additionalProperties is not provided. Default to true. (default: true)\n  --strict-objects                  Use strict validation for objects so we don't allow unknown keys. Defaults to false. (default: false)\n  -v, --version                     Display version number\n  -h, --help                        Display this message\n```\n\n## Customization\n\nYou can pass a custom [handlebars](https://handlebarsjs.com/) template and/or a [custom prettier config](https://prettier.io/docs/en/configuration.html) with something like:\n\n`pnpm openapi-zod-client ./example/petstore.yaml -o ./example/petstore-schemas.ts -t ./example/schemas-only.hbs -p ./example/prettier-custom.json --export-schemas`, there is an example of the output [here](./examples/schemas-only/petstore-schemas.ts)\n\n## When using the CLI\n\n-   `--success-expr` is bound to [`isMainResponseStatus`](https://github.com/astahmer/openapi-zod-client/blob/b7717b53023728d077ceb2f451e4787f32945b3d/src/generateZodClientFromOpenAPI.ts#L234-L244)\n-   `--error-expr` is bound to [`isErrorStatus`](https://github.com/astahmer/openapi-zod-client/blob/b7717b53023728d077ceb2f451e4787f32945b3d/src/generateZodClientFromOpenAPI.ts#L245-L256)\n\nYou can pass an expression that will be safely evaluted (thanks to [whence](https://github.com/jonschlinkert/whence/)) and works like `validateStatus` from axios to determine which OpenAPI `ResponseItem` should be picked as the main one for the `ZodiosEndpoint[\"response\"]` and which ones will be added to the `ZodiosEndpoint[\"errors\"]` array.\n\nExemple: `--success-expr \"status \u003e= 200 \u0026\u0026 status \u003c 300\"`\n\n## Tips\n\n-   You can omit the `-o` (output path) argument if you want and it will default to the input path with a `.ts` extension: `pnpm openapi-zod-client ./input.yaml` will generate a `./input.yaml.ts` file\n-   Since internally we're using [swagger-parser](https://github.com/APIDevTools/swagger-parser), you should be able to use an URL as input like this:\n    `pnpx openapi-zod-client https://raw.githubusercontent.com/OAI/OpenAPI-Specification/main/examples/v3.0/petstore.yaml -o ./petstore.ts`\n\n-   Also, multiple-files-documents ($ref pointing to another file) should work out-of-the-box as well, but if it doesn't, maybe [dereferencing](https://apitools.dev/swagger-parser/docs/swagger-parser.html#dereferenceapi-options-callback) your document before passing it to `openapi-zod-client` could help\n-   If you only need a few portions of your OpenAPI spec (i.e. only using a few endpoints from the [GitHub REST API OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification)), consider using [openapi-endpoint-trimmer](https://github.com/aacitelli/openapi-endpoint-trimmer) to trim unneeded paths from your spec first. It supports prefix-based omitting of paths, helping significantly cut down on the length of your output types file, which generally improves editor speed and compilation times.\n\n## Example\n\n-   You can check an example [input](./examples/petstore.yaml) (the petstore example when you open/reset [editor.swagger.io](https://editor.swagger.io/)) and [output](./examples/basic/petstore-client.ts)\n-   there's also [an example of a programmatic usage](./examples/basic/petstore-generator.ts)\n-   or you can check the tests in the `src` folder which are mostly just inline snapshots of the outputs\n\n# tl;dr\n\n[input](./samples/v3.0/petstore.yaml):\n\n```yaml\nopenapi: \"3.0.0\"\ninfo:\n    version: 1.0.0\n    title: Swagger Petstore\n    license:\n        name: MIT\nservers:\n    - url: http://petstore.swagger.io/v1\npaths:\n    /pets:\n        get:\n            summary: List all pets\n            operationId: listPets\n            tags:\n                - pets\n            parameters:\n                - name: limit\n                  in: query\n                  description: How many items to return at one time (max 100)\n                  required: false\n                  schema:\n                      type: integer\n                      format: int32\n            responses:\n                \"200\":\n                    description: A paged array of pets\n                    headers:\n                        x-next:\n                            description: A link to the next page of responses\n                            schema:\n                                type: string\n                    content:\n                        application/json:\n                            schema:\n                                $ref: \"#/components/schemas/Pets\"\n                default:\n                    description: unexpected error\n                    content:\n                        application/json:\n                            schema:\n                                $ref: \"#/components/schemas/Error\"\n        post:\n            summary: Create a pet\n            operationId: createPets\n            tags:\n                - pets\n            responses:\n                \"201\":\n                    description: Null response\n                default:\n                    description: unexpected error\n                    content:\n                        application/json:\n                            schema:\n                                $ref: \"#/components/schemas/Error\"\n    /pets/{petId}:\n        get:\n            summary: Info for a specific pet\n            operationId: showPetById\n            tags:\n                - pets\n            parameters:\n                - name: petId\n                  in: path\n                  required: true\n                  description: The id of the pet to retrieve\n                  schema:\n                      type: string\n            responses:\n                \"200\":\n                    description: Expected response to a valid request\n                    content:\n                        application/json:\n                            schema:\n                                $ref: \"#/components/schemas/Pet\"\n                default:\n                    description: unexpected error\n                    content:\n                        application/json:\n                            schema:\n                                $ref: \"#/components/schemas/Error\"\ncomponents:\n    schemas:\n        Pet:\n            type: object\n            required:\n                - id\n                - name\n            properties:\n                id:\n                    type: integer\n                    format: int64\n                name:\n                    type: string\n                tag:\n                    type: string\n        Pets:\n            type: array\n            items:\n                $ref: \"#/components/schemas/Pet\"\n        Error:\n            type: object\n            required:\n                - code\n                - message\n            properties:\n                code:\n                    type: integer\n                    format: int32\n                message:\n                    type: string\n```\n\noutput:\n\n```ts\nimport { makeApi, Zodios } from \"@zodios/core\";\nimport { z } from \"zod\";\n\nconst Pet = z.object({ id: z.number().int(), name: z.string(), tag: z.string().optional() });\nconst Pets = z.array(Pet);\nconst Error = z.object({ code: z.number().int(), message: z.string() });\n\nexport const schemas = {\n    Pet,\n    Pets,\n    Error,\n};\n\nconst endpoints = makeApi([\n    {\n        method: \"get\",\n        path: \"/pets\",\n        requestFormat: \"json\",\n        parameters: [\n            {\n                name: \"limit\",\n                type: \"Query\",\n                schema: z.number().int().optional(),\n            },\n        ],\n        response: z.array(Pet),\n    },\n    {\n        method: \"post\",\n        path: \"/pets\",\n        requestFormat: \"json\",\n        response: z.void(),\n    },\n    {\n        method: \"get\",\n        path: \"/pets/:petId\",\n        requestFormat: \"json\",\n        parameters: [\n            {\n                name: \"petId\",\n                type: \"Path\",\n                schema: z.string(),\n            },\n        ],\n        response: Pet,\n    },\n]);\n\nexport const api = new Zodios(endpoints);\n\nexport function createApiClient(baseUrl: string) {\n    return new Zodios(baseUrl, endpoints);\n}\n```\n\n# TODO\n\n-   handle OA `prefixItems` -\u003e output `z.tuple`\n-   rm unused (=never referenced) variables from output\n\n# Caveats\n\nNOT tested/expected to work with OpenAPI before v3, please migrate your specs to v3+ if you want to use this\n\nYou can do so by using the official Swagger Editor: https://editor.swagger.io/ using the Edit -\u003e Convert to OpenAPI 3.0 menu\n\n## Contributing:\n\n-   A `.node-version` file has been provided in the repository root, use your preferred Node.js manager which [supports](https://github.com/shadowspawn/node-version-usage#supporting-products) the standard to manage the development Node.js environment\n-   The monorepo supports [corepack](https://nodejs.org/api/corepack.html), follow the linked instructions to locally install the development package manager (i.e. [pnpm](https://pnpm.io/))\n\n```bash\n\u003e pnpm install\n\u003e pnpm test\n```\n\nAssuming no issue were raised by the tests, you may use `pnpm dev` to watch for code changes during development.\n\nIf you fix an edge case please make a dedicated minimal reproduction test in the [`tests`](./tests) folder so that it doesn't break in future versions\n\nMake sure to generate a [changeset](https://github.com/changesets/changesets/blob/main/docs/adding-a-changeset.md) before submitting your PR.\n","funding_links":[],"categories":["TypeScript","cli"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fastahmer%2Fopenapi-zod-client","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fastahmer%2Fopenapi-zod-client","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fastahmer%2Fopenapi-zod-client/lists"}