Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

openapi-zod-client

astahmer374.9kISC1.18.3TypeScript support: included

Screenshot 2022-11-12 at 18 52 25

openapi, swagger, zod, client, zodios, generator, typescript

readme

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 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 etc

please just use tRPC or alternatives (zodios is actually a full-featured solution and not just an api client, ts-rest looks cool as well) if you do have control on your API/back-end

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

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
  -a, --with-alias          With alias as api client methods
  --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
  --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
  -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

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

Contributing:

  • pnpm i && pnpm gen

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

changelog

1.4.18 (2023-01-16)

Bug Fixes

  • #67: treat null with higher priority (9f633cc), closes #67
  • handle invalid number+enum case if schema.type is Array (07e5133)

Features

  • #60: support schema.type list from openapi 3.1 (519de14), closes #60
  • playground: add api.doc.json default tab (75edaf1)

1.4.17 (2023-01-09)

1.4.16 (2023-01-05)

Bug Fixes

  • #61: Combination of enum and minLength leads to invalid zod schmemas (0c12414), closes #61

1.4.15 (2022-12-13)

Bug Fixes

  • missing zod chains on z.object(..) refs props (9b5c2cb)

1.4.14 (2022-12-13)

Bug Fixes

  • schema.type = number with string default should be inlined as number (b2786b9)

1.4.13 (2022-12-12)

Bug Fixes

  • autofix wrong schema.type case as QoL improvement (e589663)

1.4.12 (2022-12-12)

Bug Fixes

  • #49: escape control characters (5b061cf), closes #49

1.4.11 (2022-12-12)

Bug Fixes

  • ParameterObject with missing schema AND content (20e075c)

1.4.10 (2022-12-12)

Bug Fixes

  • ParameterObject with content (and no schema) (a7533a5)

1.4.8 (2022-12-11)

Bug Fixes

  • rm sheep & re-publish since it broke the package.. (794721a)

1.4.7 (2022-12-11)

Bug Fixes

  • #49: min+max shouldnt mean EXACT but between (d394d86), closes #49
  • #49: missing .and for allOf (fb2fc0c), closes #49

1.4.6 (2022-12-10)

Bug Fixes

  • #49: numerical enum shouldnt be wrapped in quotes + dont append .int() for them (cc1ced0), closes #49

1.4.5 (2022-12-07)

Bug Fixes

  • #45: add guard on possibly undefined value (be431b6), closes #45
  • getZodVarName when result is a ref with chains (17a7091)
  • schema.pattern when not wrapped with /xxx/ (bda6ecb)

Features

  • allow passing own instance of handlebars to generateZodClientFromOpenAPI (3675691)

1.4.0 (2022-11-17)

Bug Fixes

  • add updateOutput action where needed (e9b376f)
  • build (2d201bf)
  • build + preview + dev (still gets hydration mismatch) (1659ecb)
  • check for url length before history.replace/copy to clipboard (dccff7b)
  • ci (c2b0ece)
  • ci ? (4d4e720)
  • ci ?? (0fd0a03)
  • circular refs detection (d48fad2)
  • examples (9501d4b)
  • handle refs with dots in name (7a1a69d)
  • is it fine now please (b119d70)
  • lib deps (fee2ce3)
  • lib: group xxx-file should ignore options.apiClientName (65b4c43)
  • lib: normalize schema names in template context (d5705dd)
  • lock (5fa9865)
  • missing graphs dependencies (465e06f)
  • monorepo build (68d7190)
  • mv preconstruct scripts to root (6f42e65)
  • output TabsList x-axis overflow scroll (987ff76)
  • playground: catch & log errors & notify user (3fd1186)
  • playground: display parsing error (560d155)
  • playground: reset groupStrategy to none for schemas-only preset template (4aca386)
  • pnpx add postinstall in root package (a11a574)
  • pnpx by removing src in files ? (64c74a7)
  • pnpx maybe (2e3b004)
  • pnpx with postinstall (2360ef9)
  • preconstruct / babel ? (e0ccf2b)
  • presetTemplate checked (8f622bd)
  • server-side package with ssr external + rakkas preview (a48ea7e)
  • simplify output templateString (71a6810)
  • update selected template/doc on input when it was empty or when removing file tab (c851903)
  • use fs-extra version that support esm.. (76a6025)
  • using exports ? (eddfcfe)

Features

  • Actions menu wip + initial template file tab (270d7ab)
  • cli: add --api-client-name option (deca178)
  • export getHandlesbars / maybePretty (ca734db)
  • FileForm.content as monaco editor (bdeff23)
  • init docusaurus + vanilla-extract + monaco (f7e09a5)
  • input files list + editable + reset to petstore btn (1549de4)
  • lib: options.willSuppressWarnings (5ae86e5)
  • lib: whence.functions = true (ab1041f)
  • options builder + preview cli options/ts usage with copy button (78aed6a)
  • playground: add zod + @zodios/core declarations to monaco (5e53982)
  • playground: customizable prettier config + multiple prettier tabs (bf68177)
  • playground: go to file (e28e409)
  • playground: PoC for in-browser lib usage (772e301)
  • playground: prettier schema in editor (331e0a8)
  • playground: support groupStrategy xxx-file (26263f7)
  • save current state to URL & copy to clipboard (b85b1a6)
  • selectedOpenApiFileName/selectedTemplateName (c44b400)
  • SplitPane: options + fix overflow auto on 2nd pane (69b1b2b)
  • updateSelectedTemplateName with override options (9276cb4)
  • useState/Memo -> Playground.machine (ab0b863)

1.0.0 (2022-10-26)

Bug Fixes

  • add full zod chains for parameters (b4e5af1)
  • response acceptance condition should not take default (2b15d15)

Features

  • adds z.default(xxx) (1e791f2)
  • CLI: add --default-status option (181ac76)
  • options.defaultStatusBehavior (3c3456f)
  • requestFormat binary, form-url, form-data, text (099d9da)

0.9.0 (2022-10-25)

Features

  • options.complexityThreshold (dd361cc)
  • same schema different name will be re-used (ed3e320)

Reverts

0.8.0 (2022-10-24)

Features

  • options.apiClientName + custom for groups (846ae52)
  • basic --group-strategy option implementation (596e9d4)
  • group-strategy: xxx-file common.ts + index.ts (a0c3170)
  • include transitive dependencies / sort schemas by deps order + getRefName (682b0e3)

0.7.0 (2022-10-21)

0.6.1 (2022-10-20)

0.6.0 (2022-10-20)

Bug Fixes

0.5.0 (2022-10-19)

Bug Fixes

  • #15: handle missing operationId for requestBody var name (2d85f42), closes #15
  • #21: infer missing schema as z.void() when no matching MediaTypeObject or no ContentObject (4aa9180), closes #21
  • $ref in another file (dcef06a)
  • add fallback to requestBody.content (dc0895e)
  • add missing default response (704d28f)
  • also generate types for deep dependencies of circular ref types (cc616ea)
  • autofix unusual ref format (3521840)
  • cli: append .client after .yaml (88b86b0)
  • cli: v0.0.7 generateZodClientFromOpenAPI templatePath (d23069e)
  • default schemas overriding 200 response (c746ef5)
  • do not fail if schema doesn't exist (e7aa1ad)
  • getZodClientTemplateContext: replacer / variables order by dependencies (ca918dd)
  • handle refs without var name (such as arrays) (3a613e7)
  • issue#2: format path param (1896dfb), closes issue#2
  • kebab-case-in-props name should be normalized (0127722)
  • makeRefHash add letter as prefix (b1ca8cb)
  • missing maybeReplaceTokenOrVarnameWithRef on errors schema (2c08ba0)
  • openApiToTypescript openapi integer -> bigint (943f864)
  • openApiToTypescript with enum as root (098a8ad)
  • outputs all deep dependencies as TS for each circular schema (868107f)
  • reduce unions to single type when oneOf/anyOf/allOf length is 1 (d042afb)
  • reverse order of schema kind in getOpenApiDependencyGraph (091d469)
  • rm bigint -> number (b0c2181)
  • rm options.baseUrl default value (4654ab4)
  • rm unnecessary .optional() (7c46eac)
  • unintentional shared context -> make a new object (5e80cee)
  • use asApi helper rather than as const (59ee30b)
  • var names starting with number (74c72db)
  • visit additionalProperties to determine schema deps (15e3f5f)

Features

  • --with-deprecated option (defaults to false) (9a20e6f)
  • #13: implement zodios errors (216cca1), closes #13 #12
  • #19: --export-schemas option (ed8d7bd), closes #19
  • #23: withImplicitRequiredProps option (31adcc2), closes #23
  • #24: add path params (82094e9), closes #24
  • cli: -b, -a, -h, -v options (bc6c249)
  • cli: add template/prettier args (a8e8ba7)
  • export getOpenApiDependencyGraph (25eb3e3)
  • generate TS types so that z.lazy is typed properly (635d0f5)
  • infer as object when type not set but properties/additionalProperties is (bdb220b)
  • isMediaTypeAllowed option (46bf611)
  • mark recursive schemas with @circular token (1944f41)
  • openApiToTypescript with tanu.js (b4f8352)
  • openApiToTypescript: handle additionalProperties (101e1b0)
  • string/number/array validations + format #8 + #9 (e4d6354)