• Stars
    star
    753
  • Rank 60,280 (Top 2 %)
  • Language
    TypeScript
  • Created over 2 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Generate a zodios (typescript http client with zod validation) from an OpenAPI spec (json/yaml)

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

  • 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

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

More Repositories

1

typed-openapi

Generate a headless Typescript API client from an OpenAPI spec
TypeScript
183
star
2

box-extractor

Static code extraction. Zero-runtime CSS-in-TS `<Box />` -> became a part of Panda CSS
TypeScript
128
star
3

tw2panda

Easily migrate code from tailwind to Panda CSS
TypeScript
115
star
4

pandabox

a toolbox for Panda CSS
TypeScript
47
star
5

panda-monorepo

example of a panda monorepo usage with a consuming app and multiple ui-lib providers
TypeScript
40
star
6

jotai-yjs

jotai-yjs makes yjs state even easier
TypeScript
36
star
7

panda-monorepo-setup

Panda monorepo setup examples
31
star
8

partyrpc

Partykit + RPC. Move Fast (and Break Everything). Everything is better with typesafety.
TypeScript
30
star
9

crepe-ui

🥞 a Chakra UI port using Panda + Ark-UI
TypeScript
17
star
10

transformer

Takes an input (ex: TS) and ouputs to destination format (ex: Zod/JSON/Open API Schemas)
TypeScript
13
star
11

pastable

📦 A collection of pastable code gathered from past projects
TypeScript
12
star
12

vite-react-chakra-ts

Front SPA with: React 18+ / Typescript 4.7+ / Vite / Chakra-UI / React-Router / Jotai / XState / axios + react-query
TypeScript
9
star
13

typemorph

what if zod had a child with ts-morph
TypeScript
8
star
14

astahmer.dev

TypeScript
5
star
15

entity-routes

Design your REST API around your TypeORM entities in minutes. Instant CRUD with a single @EntityRoute decorator. Compatible with Koa/Express and any Connect based middleware.
TypeScript
5
star
16

vite-kikko-models

very early PoC of making offline-first easy using kikko/kysely/mikro-orm
TypeScript
4
star
17

lightningcss-ast-viewer

LightningCSS AST viewer.
TypeScript
4
star
18

entity-validator

Entity(Class) level validator based on class-validator interfaces
TypeScript
3
star
19

eslint-config

JavaScript
2
star
20

panda-tw

JavaScript
2
star
21

partykit-typeschema

TypeScript
2
star
22

vite-react-ts

TypeScript
2
star
23

panda-vite-template

TypeScript
2
star
24

vite-react-tamagui-ts

TypeScript
2
star
25

vite-react-ssr

TypeScript
1
star
26

vite-r3f

same as vite-react-chakra-ts but with react-three-fiber deps & AppCanvas/CameraControls
TypeScript
1
star
27

r3f-experiment

TypeScript
1
star
28

xstate-actors-example

TypeScript
1
star
29

rakkas-vanilla-extract-issue

TypeScript
1
star
30

sandbox-next-ts-chakra

TypeScript
1
star
31

superturk

TypeScript
1
star
32

tsc-runtime-type-benchmarks

benchmarking tsc speed across runtime type libraries
TypeScript
1
star
33

vite-r3flex-issue

repository made for an issue reproduction
TypeScript
1
star
34

box-extractor-ve-demo

Zero-runtime CSS-in-TS `<Box />` demo
TypeScript
1
star
35

astahmer.dev-astro

Astro
1
star
36

astahmer.dev-vite-plugin-ssr

TypeScript
1
star
37

vanilla-theme

TypeScript
1
star
38

vite-kikko-issue-repro

TypeScript
1
star
39

ts-lib-template

TypeScript
1
star
40

tailwind-to-css-in-js

TypeScript
1
star
41

box-extractor-vanilla-wind-demo

TypeScript
1
star
42

ve-dev-ssr-bug-repro

TypeScript
1
star