Project Icon

openapi-zod-client

从OpenAPI规范生成TypeScript HTTP客户端

openapi-zod-client是一个从OpenAPI规范生成TypeScript HTTP客户端的工具。它生成基于Zod验证的类型安全API客户端,支持CLI和编程方式使用。该工具适用于集成第三方API场景,可自动化API集成过程,提高开发效率。支持自定义模板和Prettier配置,灵活适应不同项目需求。

npm version

openapi-zod-client

Screenshot 2022-11-12 at 18 52 25

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

Why this exists

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

Comparison vs tRPC zodios ts-rest etc

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.

Comparison vs typed-openapi

  • openapi-zod-client is a CLI that generates a zodios API client (typescript http client with zod validation), currently using axios as http client
  • 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)

Usage

with local install:

  • pnpm i -D openapi-zod-client
  • pnpm 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"

auto-generated doc

https://paka.dev/npm/openapi-zod-client

CLI

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

Customization

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

When using the CLI

You 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"

Tips

  • 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.

Example

tl;dr

input:

openapi: "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);
}

TODO

  • handle OA prefixItems -> output z.tuple
  • rm unused (=never referenced) variables from output

Caveats

NOT 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

Contributing:

  • A .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
  • The monorepo supports corepack, follow the linked instructions to locally install the development package manager (i.e. pnpm)
> 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

项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

白日梦AI

白日梦AI提供专注于AI视频生成的多样化功能,包括文生视频、动态画面和形象生成等,帮助用户快速上手,创造专业级内容。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

讯飞绘镜

讯飞绘镜是一个支持从创意到完整视频创作的智能平台,用户可以快速生成视频素材并创作独特的音乐视频和故事。平台提供多样化的主题和精选作品,帮助用户探索创意灵感。

Project Cover

讯飞文书

讯飞文书依托讯飞星火大模型,为文书写作者提供从素材筹备到稿件撰写及审稿的全程支持。通过录音智记和以稿写稿等功能,满足事务性工作的高频需求,帮助撰稿人节省精力,提高效率,优化工作与生活。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号