Valibot
Generate Valibot schemas from OpenAPI
Generate Valibot schemas from your OpenAPI specification for runtime validation. The generated code needs valibot 1.0 or newer:
npm install valibotChoosing a Mode
client: 'valibot' | schemas: { type: 'valibot' } | |
|---|---|---|
| Use it to | Parse and validate data yourself | Make a generated HTTP client validate its responses |
| Generates | A schema for the params, query, headers, body and response of each operation | A schema for each model, and for each operation's query params and headers, plus its request body and responses when they are not a $ref |
| Type names | None, except on recursive schemas with generateReusableSchemas: Pet is the output, PetInput the input | Every schema: Pet is the input, PetOutput the output |
To use both, generate them in separate outputs. See Combining with HTTP Clients.
Configuration
Set the client option to valibot:
import { defineConfig } from 'orval';
export default defineConfig({
petstore: {
output: {
client: 'valibot',
mode: 'single',
target: './src/api/schemas.ts',
},
input: {
target: './petstore.yaml',
},
},
});Generated Output
Orval generates a Valibot schema for the params, query, headers, body and response of each operation. The body and response schemas come from JSON, multipart/form-data or application/x-www-form-urlencoded content, and the response schema from the first of 200, 2XX/2xx and the other 2xx responses (except 204 and 205) that has such content. Other media types, such as text/plain, get no schema:
import * as v from 'valibot';
export const CreatePetsBody = v.object({
id: v.pipe(v.number(), v.integer()),
name: v.string(),
tag: v.optional(v.string()),
});Options
Options live under override.valibot:
strict- per location (param,query,header,body,response), emitv.strictObjectinstead ofv.object. Allfalseby default.generate- per location, choose which schemas are generated. Alltrueby default.exactOptional- usev.exactOptionalfor optional properties, for projects withexactOptionalPropertyTypes.falseby default. Can also be set per operation or tag.generateReusableSchemas- emit each component schema once and reference it, instead of inlining every$ref.falseby default. See Reusable Schemas.
Reusable Schemas
By default every $ref is inlined, which makes the output large for a spec with many shared components. With generateReusableSchemas, each #/components/schemas/* entry becomes one exported constant:
export default defineConfig({
petstore: {
output: {
client: 'valibot',
target: './src/api/schemas.ts',
override: { valibot: { generateReusableSchemas: true } },
},
input: { target: './petstore.yaml' },
},
});export type Pet = {
name: string;
friends?: Pet[] | undefined;
};
export type PetInput = {
name: string;
friends?: PetInput[] | undefined;
};
export const Pet = v.object({
name: v.string(),
friends: v.optional(
v.array(v.lazy((): v.GenericSchema<PetInput, Pet> => Pet)),
),
});
export const ListPetsResponse = v.array(Pet);The constants go next to the operations: into the target in single mode, into a *.schemas.ts file in the other modes. A reference that closes a cycle reads through v.lazy.
Each constant on a cycle also gets two exported types: Pet for its output and PetInput for its input. The v.lazy getter uses them, so the recursive field is typed Pet[] instead of unknown. When another schema already has the name PetInput, the input type becomes PetInput2. A field converted by an inline formatType decode, such as (value) => dayjs(value), is typed unknown in these types. Name a function, such as 'dayjs', to type it with that function's return type.
Limitations
- With
client: 'valibot',generateReusableSchemasandoutput.schemascan't be set together: generation fails with an error. To write the schemas to their own module, setschemas.typetovalibotwith an HTTP client. - A
$refis still inlined where a constant would validate differently, such as form bodies,readOnlyandwriteOnlyproperties, and someallOf,oneOfandanyOfmembers. - A constant keeps all its properties and is
strictonly when every location is. A location with a differentstrict, or an operation override ofexactOptional, inlines its schemas. - A
oneOforanyOfwith adiscriminatorbecomesv.unionwhen an option is a reference. - A component named
DateorRegExpgets aSchemasuffix. Two components with the same name stop generation with an error.
Checking Against the Models
Models and schemas come from separate generators, so they can drift apart without anyone noticing. When a project generates TypeScript models in another configuration, the shared override.modelTypeChecks option, which also works with Zod, makes the schemas file assert that each component schema outputs what its model declares:
export default defineConfig({
api: {
output: {
client: 'fetch',
target: './src/api/endpoints.ts',
schemas: './src/api/model',
},
input: { target: './petstore.yaml' },
},
validation: {
output: {
client: 'valibot',
target: './src/validation/schemas.ts',
override: {
valibot: { generateReusableSchemas: true },
modelTypeChecks: { models: './src/api/model' },
},
},
input: { target: './petstore.yaml' },
},
});models is the directory the other configuration writes its models to, like its output.schemas. A relative path starts at the workspace of this configuration, which can differ from that of the other one, and an absolute path is used as it is. The schemas file imports it and gets a type-only block. Nothing changes at runtime:
import type * as Models from '../api/model';
type Assert<T extends true> = T;
type Extends<A, B> = [A] extends [B] ? true : false;
type SchemaModelTypeChecks = {
Pet: [
Assert<Extends<v.InferOutput<typeof Pet>, Models.Pet>>,
Assert<Extends<Models.Pet, v.InferOutput<typeof Pet>>>,
];
};
declare const schemaModelTypeChecks: SchemaModelTypeChecks;The type is not exported, so a barrel that re-exports several of these files does not clash on it. The ambient declare const reads it, so noUnusedLocals stays quiet, and it emits no code.
When a schema and its model are not assignable both ways, your own tsc run fails on the assertion of that component, with Type 'false' does not satisfy the constraint 'true'.
- Both configurations must use the same naming options, such as
override.components.schemas, so a model has the name of its schema. - Assignability in both directions does not catch an optional property that only one side declares, nor a type that is
anyon either side. Required properties, nullability,readonlyarrays, enums, unions and nested or recursive types are caught. - The check imports the
index.tsof the models and needs it to export every component by name. KeepindexFileson, which is the default, in the configuration that writes the models. - An option such as
formatTypeoruseDatesthat maps a type in the schemas must map it in the models too. SetuseBigIntanduseReadonlyArraysin both configurations, so the checks skip the components they change. - With
exactOptionalPropertyTypesin yourtsconfig, the models type an optional property asa?: T, so setexactOptional: trueinoverride.valibot, or every optional property fails the check. Orval warns at generation when thetsconfigit reads sets the flag andexactOptionalis off. modelTypeChecksrejectsuseBrandedTypes,useNullForOptional,enumGenerationType: 'enum'andnamingConvention.propertieswith an error, because they shape the models in ways a schema output cannot match. A TypeScriptenumis not assignable from the string literals a schema outputs, so use'const'or'union'in the configuration that writes the models too.
Skipped components
Orval types some schemas more loosely than their models on purpose, so no schema could match the model there. A component that holds one has no assertion. A comment in the block says why, so the file still compiles:
type SchemaModelTypeChecks = {
Pet: [
Assert<Extends<v.InferOutput<typeof Pet>, Models.Pet>>,
Assert<Extends<Models.Pet, v.InferOutput<typeof Pet>>>,
];
// Point: skipped, prefixItems is validated as an array of unknown
};
declare const schemaModelTypeChecks: SchemaModelTypeChecks;A component that references a skipped one is skipped too, because its output type holds the other's. The constructs are:
prefixItems(a tuple) is validated as an array ofunknown.- A circular reference that cannot be kept is validated as
unknown. - A binary string, such as
format: binary, is validated asFile, and the model types it asBlob. - A
defaulton an optional property makes the key required in the output only. For Valibot, this includes a property that references a schema with adefault. additionalPropertiesnext topropertiesis typed asunknownby the model, and the schema checks it.- An
enumallOfmember next to thepropertiesof the same schema is an alternative in the model and is intersected in the schema. - A schema without a type, such as
{}or one with only adescription, is validated asunknown, and the model types it as{}. - A schema without a type that only describes an object, with
additionalProperties,patternPropertiesor an emptyproperties, is validated asunknownat any depth, in a property or anallOfmember too, and the model types it as an object. - A
constthat is an object or an array is not validated, and anenumwith such a member is validated asunknown. - A required key that no property declares, such as
required: [id]withoutproperties, is validated asunknown, and the model leaves it out. - A key that a
oneOforanyOfschema requires while only its alternatives declare it, such asrequired: [id]next to an alternative that listsidas optional, is required in each alternative that declares it, and the model leaves each one as it declares it. - A
oneOforanyOfalternative that only requires keys, such as{ required: [id] }, next to the properties of an object, is validated as an object with those keys, and the model types it asunknown. - With
useBigInt, a 64-bit integer (format: int64oruint64) is abigintin the model and anumberin the schema. - With
useReadonlyArrays, an array isreadonlyin the model, and the schema output is not. - A
readOnlybeside a reference to an array makes the outputreadonly, which the model does not. - A
readOnlyarray in theitemsof an array isreadonlyin the schema, and the model putsreadonlyon the outer array. - A
constwithnullin itstypeis typed withoutnullby the model. - A component whose properties are all a
constis written as a constant object by the model, so every key is required. A component with an optional one differs from the schema. - A
oneOforanyOfwith anull, nullable orenumalternative, next to thepropertiesorallOfof the same schema: the model merges the alternatives and drops the own properties of an enum, and the schema intersects them.
Usage
Parsing Data
import * as v from 'valibot';
import { CreatePetsBody } from './src/api/schemas';
const pet = v.parse(CreatePetsBody, { id: 1, name: 'Buddy', tag: 'dog' });
// => { id: 1, name: "Buddy", tag: "dog" }Type Inference
import * as v from 'valibot';
import { CreatePetsBody } from './src/api/schemas';
type Pet = v.InferOutput<typeof CreatePetsBody>;
const pet: Pet = { id: 1, name: 'Buddy', tag: 'dog' };Safe Parsing
import * as v from 'valibot';
import { CreatePetsBody } from './src/api/schemas';
const result = v.safeParse(CreatePetsBody, unknownData);
if (result.success) {
console.log(result.output);
} else {
console.error(result.issues);
}Mapping
oneOfandanyOfbecomev.union, orv.variantwhen adiscriminatoris set.allOfbecomesv.intersect.- Objects strip unknown keys. The
strictoption emitsv.strictObject, andadditionalPropertiesemitsv.looseObjectorv.record. dateanddate-timestrings are validated as ISO dates, and adate-timeneeds an offset such asZ. Withoverride.useDatesthey are converted toDate.- Binary fields (
format: binary) becomev.file(), including file parts inmultipart/form-databodies. readOnlyproperties are left out of request bodies, andwriteOnlyproperties out of responses. AreadOnlyarray withitemsgetsv.readonly(), so its output is a readonly array, as in the model.suppressReadonlyModifierturns this off for both.- A
defaultthat does not fit its schema is left out, with a warning.
Limitations
- A circular
$refis validated asunknown, with a warning, wherever it is inlined. WithgenerateReusableSchemas, component constants validate recursively throughv.lazy. prefixItemstuples are validated asunknown[], with a warning.- When an item of a
readOnlyarray fails a check, valibot skips the array's own checks, such asmaxItems. Av.unionaround the array, or around an object that contains it, then reports one generic issue instead of the item's issue. A date conversion orformatTypedecoder has the same effect on a string that fails a check. - Every
$refis inlined unlessgenerateReusableSchemasis set, so shared schemas can make the output large. Inlining one schema stops with an error past 250,000 schema nodes. oneOfdoes not check that exactly one alternative matches.- Query and path params are not coerced: a number read from a URL string fails
v.number(). Header keys keep the casing of the spec. - Inside an
allOfintersection,strictobjects are emitted asv.object, so extra keys are stripped instead of rejected. An open member (additionalProperties: true) next to an object member is left out, so extra keys are stripped too.
Validating HTTP Client Responses
Set schemas.type to valibot and turn on the client's runtimeValidation. The generated client then validates responses with Valibot schemas instead of Zod.
export default defineConfig({
petstore: {
output: {
client: 'fetch',
target: './src/api/endpoints.ts',
schemas: { path: './src/api/model', type: 'valibot' },
override: {
fetch: { runtimeValidation: true },
},
},
input: { target: './petstore.yaml' },
},
});Every schema goes to one module, <schemas.path>/index.valibot.ts, or schemas.path itself when it names a file. There is no index.ts barrel, so here you import from ./src/api/model/index.valibot. Each schema also exports the types X (v.InferInput) and XOutput (v.InferOutput). A schema on a cycle declares both types in full instead, because they cannot be inferred, so its recursive fields keep their types.
- Validation runs through the
runtimeValidationoption ofoverride.fetchforfetchand forreact-query,vue-query,svelte-query,solid-query,swr,pinia-coladawithhttpClient: 'fetch',override.angularforangular, andoverride.queryforangular-query. It is off by default. standardSchemais always on, because Valibot schemas have noparsemethod. Validation errors are thereforeStandardSchemaError, notValiError, sov.isValiError()is false for them. Readerror.issues. Async schemas are not supported.- Axios clients do not validate.
- Generated validation is skipped for custom mutators. With
includeSchemaInArguments, the custom mutator offetchor a fetch-backed client receives the schema asschemaand validates the response itself throughschema['~standard'].validate(). Angular clients do not pass the schema to a mutator. useDatesmakes the schemas turn date strings intoDate, soXOutputhasDatewhereXhasstring.useDatesTransformturns onuseDatesand nothing more: the client adds no date deserializer.
The following fail with a configuration error: schemas.mode: 'split', schemas.routes, schemas.splitByTags, mock generators (for MSW, add a second output with TypeScript models), operationSchemas, factoryMethods, splitByContentType, standardSchema: false, override.formatType, override.useBigInt, override.namingConvention.properties, Angular runtimeValidation.requestBodies with useDates, and the clients zod, effect, valibot, hono and mcp.
Known limits:
- With the fetch clients and the default
forceSuccessResponse: false, a JSON error response is validated against the success schema, whatever its status. A404body that does not fit the schema throws aStandardSchemaError, and one that fits passes. Zod does the same. WithforceSuccessResponse: true, and in the Angular clients, an error status is not validated. - Requests and responses share a component schema, so a required
writeOnlyproperty is optional in it, and a requiredreadOnlyproperty is still required in request body types. format: binarymaps tov.file()also in JSON, so a JSON response with such a property fails validation. A binary value is typedFile, notBlob.
See the Valibot with fetch sample on GitHub. It has one output that validates in the generated client, and one with a mutator that validates through ~standard.
Combining with HTTP Clients
The valibot client generates schemas only. To have an HTTP client validate its responses, use schemas.type instead.
To use the valibot client next to an HTTP client, for example to check a request body before sending it, generate each in its own output. Give each output its own target, or the Valibot output overwrites the client files. In tags and tags-split mode the file name of a target is ignored and only its directory counts: with the default file extension, http.ts and validation.ts in one directory both write pets.ts for the tag pets. Use separate directories there, or set fileExtension: '.valibot.ts' on the Valibot output so the two can share one. The same setting lets split mode share a directory target such as ./src/api. A shared file target can still collide: ./src/api/endpoints.valibot.ts makes both outputs write endpoints.valibot.ts.