Skip to main content

Zod

To create a Zod schema, specify the client property as zod, and it will automatically be generated in the target file. Ensure that Zod is configured properly in your project by referring to the Zod documentation.

Example of orval.config.js

module.exports = {
petstore: {
output: {
client: 'zod',
mode: 'single',
target: './src/gen/zod',
},
input: {
target: './petstore.yaml',
},
},
};

An implementation file will be created, containing a Zod object for each schema in your OpenAPI Specification, as illustrated below:

export const createPetsBody = zod.object({
id: zod.number(),
name: zod.string(),
tag: zod.string().optional(),
});

How to Use the Generated Zod Object

The Zod object generated automatically can be utilized in the usual manner.

import type { z } from 'zod';
import { createPetsBodyItem } from './src/gen/zod/swaggerPetstore.ts';
const pet = { id: 1, name: 'pet name', tag: 'tag' };
// parsing
const parsedPet = createPetsBodyItem.parse(pet);
console.log(parsedPet);
// => Object { id: 1, name: "pet name", tag: "tag" }
// inferred type
type Pet = z.infer<typeof createPetsBodyItem>;
console.log(pet as Pet);
// => Object { id: 1, name: "pet name", tag: "tag" }
Was this page helpful?