Gathering detailed insights and metrics for openapi-zod-client
Gathering detailed insights and metrics for openapi-zod-client
Gathering detailed insights and metrics for openapi-zod-client
Gathering detailed insights and metrics for openapi-zod-client
Generate a zodios (typescript http client with zod validation) from an OpenAPI spec (json/yaml)
npm install openapi-zod-client
openapi-zod-client@1.18.2
Published on 31 Jul 2024
openapi-zod-client@1.18.1
Published on 18 Apr 2024
openapi-zod-client@1.18.0
Published on 13 Apr 2024
openapi-zod-client@1.17.0
Published on 11 Apr 2024
openapi-zod-client@1.16.4
Published on 03 Apr 2024
openapi-zod-client@1.16.3
Published on 26 Mar 2024
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
820 Stars
590 Commits
89 Forks
3 Watching
8 Branches
40 Contributors
Updated on 27 Nov 2024
TypeScript (98.88%)
Handlebars (0.47%)
JavaScript (0.34%)
HTML (0.18%)
CSS (0.12%)
Cumulative downloads
Total Downloads
Last day
1.2%
11,860
Compared to previous day
Last week
-9.2%
57,047
Compared to previous week
Last month
22.5%
273,212
Compared to previous month
Last year
401%
1,828,446
Compared to previous year
14
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-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"
https://paka.dev/npm/openapi-zod-client
1openapi-zod-client/1.15.0 2 3Usage: 4 $ openapi-zod-client <input> 5 6Commands: 7 <input> path/url to OpenAPI/Swagger document as json/yaml 8 9For more info, run any command with the `--help` flag: 10 $ openapi-zod-client --help 11 12Options: 13 -o, --output <path> Output path for the zodios api client ts file (defaults to `<input>.client.ts`) 14 -t, --template <path> Template path for the handlebars template that will be used to generate the output 15 -p, --prettier <path> Prettier config path that will be used to format the output client file 16 -b, --base-url <url> Base url for the api 17 --no-with-alias With alias as api client methods (default: true) 18 -a, --with-alias With alias as api client methods (default: true) 19 --api-client-name <name> when using the default `template.hbs`, allow customizing the `export const {apiClientName}` 20 --error-expr <expr> Pass an expression to determine if a response status is an error 21 --success-expr <expr> Pass an expression to determine which response status is the main success status 22 --media-type-expr <expr> Pass an expression to determine which response content should be allowed 23 --export-schemas When true, will export all `#/components/schemas` 24 --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 25 --with-deprecated when true, will keep deprecated endpoints in the api output 26 --with-description when true, will add z.describe(xxx) 27 --with-docs when true, will add jsdoc comments to generated types 28 --group-strategy groups endpoints by a given strategy, possible values are: 'none' | 'tag' | 'method' | 'tag-file' | 'method-file' 29 --complexity-threshold schema complexity threshold to determine which one (using less than `<` operator) should be assigned to a variable 30 --default-status when defined as `auto-correct`, will automatically use `default` as fallback for `response` when no status code was declared 31 --all-readonly when true, all generated objects and arrays will be readonly 32 --export-types When true, will defined types for all object schemas in `#/components/schemas` 33 --additional-props-default-value Set default value when additionalProperties is not provided. Default to true. (default: true) 34 --strict-objects Use strict validation for objects so we don't allow unknown keys. Defaults to false. (default: false) 35 -v, --version Display version number 36 -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 isErrorStatus
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"
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 outputs1openapi: "3.0.0" 2info: 3 version: 1.0.0 4 title: Swagger Petstore 5 license: 6 name: MIT 7servers: 8 - url: http://petstore.swagger.io/v1 9paths: 10 /pets: 11 get: 12 summary: List all pets 13 operationId: listPets 14 tags: 15 - pets 16 parameters: 17 - name: limit 18 in: query 19 description: How many items to return at one time (max 100) 20 required: false 21 schema: 22 type: integer 23 format: int32 24 responses: 25 "200": 26 description: A paged array of pets 27 headers: 28 x-next: 29 description: A link to the next page of responses 30 schema: 31 type: string 32 content: 33 application/json: 34 schema: 35 $ref: "#/components/schemas/Pets" 36 default: 37 description: unexpected error 38 content: 39 application/json: 40 schema: 41 $ref: "#/components/schemas/Error" 42 post: 43 summary: Create a pet 44 operationId: createPets 45 tags: 46 - pets 47 responses: 48 "201": 49 description: Null response 50 default: 51 description: unexpected error 52 content: 53 application/json: 54 schema: 55 $ref: "#/components/schemas/Error" 56 /pets/{petId}: 57 get: 58 summary: Info for a specific pet 59 operationId: showPetById 60 tags: 61 - pets 62 parameters: 63 - name: petId 64 in: path 65 required: true 66 description: The id of the pet to retrieve 67 schema: 68 type: string 69 responses: 70 "200": 71 description: Expected response to a valid request 72 content: 73 application/json: 74 schema: 75 $ref: "#/components/schemas/Pet" 76 default: 77 description: unexpected error 78 content: 79 application/json: 80 schema: 81 $ref: "#/components/schemas/Error" 82components: 83 schemas: 84 Pet: 85 type: object 86 required: 87 - id 88 - name 89 properties: 90 id: 91 type: integer 92 format: int64 93 name: 94 type: string 95 tag: 96 type: string 97 Pets: 98 type: array 99 items: 100 $ref: "#/components/schemas/Pet" 101 Error: 102 type: object 103 required: 104 - code 105 - message 106 properties: 107 code: 108 type: integer 109 format: int32 110 message: 111 type: string
output:
1import { makeApi, Zodios } from "@zodios/core"; 2import { z } from "zod"; 3 4const Pet = z.object({ id: z.number().int(), name: z.string(), tag: z.string().optional() }); 5const Pets = z.array(Pet); 6const Error = z.object({ code: z.number().int(), message: z.string() }); 7 8export const schemas = { 9 Pet, 10 Pets, 11 Error, 12}; 13 14const endpoints = makeApi([ 15 { 16 method: "get", 17 path: "/pets", 18 requestFormat: "json", 19 parameters: [ 20 { 21 name: "limit", 22 type: "Query", 23 schema: z.number().int().optional(), 24 }, 25 ], 26 response: z.array(Pet), 27 }, 28 { 29 method: "post", 30 path: "/pets", 31 requestFormat: "json", 32 response: z.void(), 33 }, 34 { 35 method: "get", 36 path: "/pets/:petId", 37 requestFormat: "json", 38 parameters: [ 39 { 40 name: "petId", 41 type: "Path", 42 schema: z.string(), 43 }, 44 ], 45 response: Pet, 46 }, 47]); 48 49export const api = new Zodios(endpoints); 50 51export function createApiClient(baseUrl: string) { 52 return new Zodios(baseUrl, endpoints); 53}
prefixItems
-> output z.tuple
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
.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 environment1> pnpm install 2> 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 PR.
No vulnerabilities found.
No security vulnerabilities found.