JSPM

  • Created
  • Published
  • Downloads 80684
  • Score
    100M100P100Q158873F
  • License ISC

Package Exports

  • openapi-zod-client
  • openapi-zod-client/dist/openapi-zod-client.cjs.js
  • openapi-zod-client/dist/openapi-zod-client.esm.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (openapi-zod-client) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

openapi-zod-client

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

  • pnpx openapi-zod-client "./input/file.yaml" -o "./output/client.ts"

CLI

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>.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
  -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, there is an example here

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 { Zodios } from "@zodios/core";
import { z } from "zod";

const v7LgRCMpuZ0 = z.object({ id: z.bigint(), name: z.string(), tag: z.string().optional() }).optional();
const vWZd2G8UeSs = z.array(v7LgRCMpuZ0).optional();
const v77smkx5YEB = z.object({ code: z.bigint(), message: z.string() }).optional();

const variables = {
    Error: v77smkx5YEB,
    Pet: v7LgRCMpuZ0,
    Pets: vWZd2G8UeSs,
    createPets: v77smkx5YEB,
    listPets: v77smkx5YEB,
    showPetById: v77smkx5YEB,
};

const endpoints = [
    {
        method: "get",
        path: "/pets",
        requestFormat: "json",
        parameters: [
            {
                name: "limit",
                type: "Query",
                schema: z.bigint().optional(),
            },
        ],
        response: variables["Pets"],
    },
    {
        method: "post",
        path: "/pets",
        requestFormat: "json",
        response: variables["Error"],
    },
    {
        method: "get",
        path: "/pets/:petId",
        requestFormat: "json",
        response: variables["Pet"],
    },
] as const;

export const api = new Zodios(endpoints);

TODO

  • handle default values (output z.default(xxx))
  • handle OA spec format: date-time -> output z.date() / preprocess ?
  • handle string/number constraints -> output z.min max length email url uuid startsWith endsWith regex trim nonempty gt gte lt lte int positive nonnegative negative nonpositive multipleOf
  • handle OA prefixItems -> output z.tuple
  • handle recursive schemas -> output z.lazy()
  • add an argument to control which response should be added (currently by status code === "200" or when there is a "default")
  • 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