OpenAPI Generator
Getting Started
Installation
npm install --save-dev @sohcah/openapi-generatorPeer Dependencies
The generated source from the OpenAPI Generator requires @tanstack/react-query and zod.
npm install @tanstack/react-query zodUsage
The generator uses a builder pattern. Each generator (referred to as a builder) is registered with a name, and downstream builders can reference upstream ones by that name. This allows the schema, request, and client layers to be composed independently.
import { defineConfig } from "@sohcah/openapi-generator/config";
import { createZodGenerator } from "@sohcah/openapi-generator/zod";
import { createFetchGenerator } from "@sohcah/openapi-generator/fetch";
import { createReactQueryGenerator } from "@sohcah/openapi-generator/react-query";
export default defineConfig({
schema: "swagger.json",
})
.addBuilder("schemas", () =>
createZodGenerator({
output: "src/api.schemas.ts",
}),
)
.addBuilder("fetch", () =>
createFetchGenerator({
output: "src/api.fetch.ts",
schemaGenerator: "schemas",
}),
)
.addBuilder("api", () =>
createReactQueryGenerator({
output: "src/api.ts",
requestGenerator: "fetch",
}),
);This produces three generated files:
src/api.schemas.ts— Zod schemas for every operation's parameters and responses.src/api.fetch.ts— aFetchApiclass that wraps afetch-compatible function and uses the generated schemas to encode parameters and parse responses.src/api.ts— anApiclass exposing TanStack Query–readyqueryOptions/mutationOptionsfor every operation, backed by theFetchApiclass.
{
"scripts": {
"openapi-build": "openapi-generator --config openapi.config.ts",
"openapi-dev": "openapi-generator --config openapi.config.ts --watch"
}
}