Generates a zodios (typescript http client with zod validation) from a (json/yaml) OpenAPI spec (or just use the generated schemas/endpoints/etc !)
can be used programmatically (do w/e you want with the computed schemas/endpoints)
or used as a CLI (generates a prettier .ts file with deduplicated variables when pointing to the same schema/$ref)
client typesafety and runtime validation using zodios
tested (using vitest) against official OpenAPI specs samples
Sometimes 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 😇
You 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
If you do have control on your API/back-end, you should probably use a RPC-like solution like tRPC, zodios or ts-rest instead of this.
openapi-zod-client is a CLI that generates a zodios API client (typescript http client with zod validation), currently using axios as http clienttyped-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)with local install:
pnpm i -D openapi-zod-clientpnpm openapi-zod-client "./input/file.json" -o "./output/client.ts"or directly (no install)
pnpx openapi-zod-client "./input/file.yaml" -o "./output/client.ts"https://paka.dev/npm/openapi-zod-client
openapi-zod-client/1.15.0 Usage: $ openapi-zod-client <input> Commands: <input> path/url to OpenAPI/Swagger document as json/yaml For more info, run any command with the `--help` flag: $ openapi-zod-client --help Options: -o, --output <path> Output path for the zodios api client ts file (defaults to `<input>.client.ts`) -t, --template <path> Template path for the handlebars template that will be used to generate the output -p, --prettier <path> Prettier config path that will be used to format the output client file -b, --base-url <url> Base url for the api --no-with-alias With alias as api client methods (default: true) -a, --with-alias With alias as api client methods (default: true) --api-client-name <name> when using the default `template.hbs`, allow customizing the `export const {apiClientName}` --error-expr <expr> Pass an expression to determine if a response status is an error --success-expr <expr> Pass an expression to determine which response status is the main success status --media-type-expr <expr> Pass an expression to determine which response content should be allowed --export-schemas When true, will export all `#/components/schemas` --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 --with-deprecated when true, will keep deprecated endpoints in the api output --with-description when true, will add z.describe(xxx) --with-docs when true, will add jsdoc comments to generated types --group-strategy groups endpoints by a given strategy, possible values are: 'none' | 'tag' | 'method' | 'tag-file' | 'method-file' --complexity-threshold schema complexity threshold to determine which one (using less than `<` operator) should be assigned to a variable --default-status when defined as `auto-correct`, will automatically use `default` as fallback for `response` when no status code was declared --all-readonly when true, all generated objects and arrays will be readonly --export-types When true, will defined types for all object schemas in `#/components/schemas` --additional-props-default-value Set default value when additionalProperties is not provided. Default to true. (default: true) --strict-objects Use strict validation for objects so we don't allow unknown keys. Defaults to false. (default: false) -v, --version Display version number -h, --help Display this message
You can pass a custom handlebars template and/or a custom prettier config with something like:
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
--success-expr is bound to isMainResponseStatus--error-expr is bound to isErrorStatusYou can pass an expression that will be safely evaluted (thanks to 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.
Exemple: --success-expr "status >= 200 && status < 300"
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
Since internally we're using swagger-parser, you should be able to use an URL as input like this:
pnpx openapi-zod-client https://raw.githubusercontent.com/OAI/OpenAPI-Specification/main/examples/v3.0/petstore.yaml -o ./petstore.ts
Also, multiple-files-documents ($ref pointing to another file) should work out-of-the-box as well, but if it doesn't, maybe dereferencing your document before passing it to openapi-zod-client could help
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), consider using 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.
src folder which are mostly just inline snapshots of the outputsopenapi: "3.0.0" info: version: 1.0.0 title: Swagger Petstore license: name: MIT servers: - url: http://petstore.swagger.io/v1 paths: /pets: get: summary: List all pets operationId: listPets tags: - pets parameters: - name: limit in: query description: How many items to return at one time (max 100) required: false schema: type: integer format: int32 responses: "200": description: A paged array of pets headers: x-next: description: A link to the next page of responses schema: type: string content: application/json: schema: $ref: "#/components/schemas/Pets" default: description: unexpected error content: application/json: schema: $ref: "#/components/schemas/Error" post: summary: Create a pet operationId: createPets tags: - pets responses: "201": description: Null response default: description: unexpected error content: application/json: schema: $ref: "#/components/schemas/Error" /pets/{petId}: get: summary: Info for a specific pet operationId: showPetById tags: - pets parameters: - name: petId in: path required: true description: The id of the pet to retrieve schema: type: string responses: "200": description: Expected response to a valid request content: application/json: schema: $ref: "#/components/schemas/Pet" default: description: unexpected error content: application/json: schema: $ref: "#/components/schemas/Error" components: schemas: Pet: type: object required: - id - name properties: id: type: integer format: int64 name: type: string tag: type: string Pets: type: array items: $ref: "#/components/schemas/Pet" Error: type: object required: - code - message properties: code: type: integer format: int32 message: type: string
output:
import { makeApi, Zodios } from "@zodios/core"; import { z } from "zod"; const Pet = z.object({ id: z.number().int(), name: z.string(), tag: z.string().optional() }); const Pets = z.array(Pet); const Error = z.object({ code: z.number().int(), message: z.string() }); export const schemas = { Pet, Pets, Error, }; const endpoints = makeApi([ { method: "get", path: "/pets", requestFormat: "json", parameters: [ { name: "limit", type: "Query", schema: z.number().int().optional(), }, ], response: z.array(Pet), }, { method: "post", path: "/pets", requestFormat: "json", response: z.void(), }, { method: "get", path: "/pets/:petId", requestFormat: "json", parameters: [ { name: "petId", type: "Path", schema: z.string(), }, ], response: Pet, }, ]); export const api = new Zodios(endpoints); export function createApiClient(baseUrl: string) { return new Zodios(baseUrl, endpoints); }
prefixItems -> output z.tupleNOT tested/expected to work with OpenAPI before v3, please migrate your specs to v3+ if you want to use this
You can do so by using the official Swagger Editor: https://editor.swagger.io/ using the Edit -> Convert to OpenAPI 3.0 menu
.node-version file has been provided in the repository root, use your preferred Node.js manager which supports the standard to manage the development Node.js environment> pnpm install > pnpm test
Assuming no issue were raised by the tests, you may use pnpm dev to watch for code changes during development.
If you fix an edge case please make a dedicated minimal reproduction test in the tests folder so that it doesn't break in future versions
Make sure to generate a changeset before submitting your


AI一键生成PPT,就用博思AIPPT!
博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。


AI赋能电商视觉革命,一站式智能商拍平台
潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。


企业专属的AI法律顾问
iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。


稳定高效的流量提升解决方案,助力品牌曝光
稳定高效的流量提升解决方案,助力品牌曝光


最新版Sora2模型免费使用,一键生成无水印视频
最新版Sora2模型免费使用,一键生成无水印视频


实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。


选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。


AI辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。


最强AI数据分析助手
小浣熊家族Raccoon,您的AI智能助手,致力于通过先进的人工智能技术,为用户提供高效、便捷的智能服务。无论是日常咨询还是专业问题解答,小浣熊都能以快速、准确的响应满足您的需求,让您的生活更加智能便捷。


像人一样思考的AI智能体
imini 是一款超级AI智能体,能根据人类指令,自主思考、自主完成、并且交付结果的AI智能体。
最新AI工具、AI资讯
独家AI资源、AI项目落地

微信扫一扫关注公众号