Output
target
Type: String.
Valid values: path to the file containing the generated code.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {target: 'src/petstore.ts',},},});
client
Type: String | Function.
Valid values: angular, axios, axios-functions, react-query, svelte-query, vue-query, swr, zod, fetch.
Default Value: axios-functions.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {client: 'react-query',},},});
The valid values specify the default client generators provided by Orval. It is possible to provide a function to extend or create a custom client generator. The function should accept a GeneratorClients argument, and should return a ClientGeneratorsBuilder.
httpClient
Type: String.
Valid values: fetch, axios.
Default Value: fetch.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {client: 'swr',},},});
The Fetch API is used as the default HTTP client. Specify axios if you want to use Axios instead.
This property is only valid when swr, react-query, vue-query, and svelte-query are specified as the client option.
schemas
Type: String.
Valid values: path to the folder where the generated models are written.
Default Value: same as the target.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {schemas: './api/model',},},});
fileExtension
Type: String.
Default Value: .ts.
Specify the file extension for files generated automatically. Modes such as tags, tags-split, and split do not alter schema files; they only pertain to client files.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {mode: 'split',target: './gen/endpoints',schemas: './gen/model',fileExtension: '.gen.ts',},},});
src/gen/├── endpoints│ └── swaggerPetstore.gen.ts└── model├── listPetsParams.ts└── pets.ts
namingConvention
Type: String.
Valid values: camelCase, PascalCase, snake_case, kebab-case.
Default Value: camelCase.
Specify the naming convention for the generated files.
If you're looking for property keys naming convention, see namingConvention.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {namingConvention: 'PascalCase',mode: 'split',target: './gen/endpoints',schemas: './gen/model',fileExtension: '.gen.ts',},},});
src/gen/├── endpoints│ └── SwaggerPetstore.gen.ts└── model├── ListPetsParams.ts└── Pets.ts
workspace
Type: String.
Valid values: path to the folder which will contains all the generated files. This value will be use as a base for all the other paths used in the Orval config.
If this option is provided, an index.ts file will also be created with all the available exports
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {workspace: 'src/'target: './petstore.ts',},},});
mode
Type: String.
Valid values: single, split, tags, tags-split.
Default Value: single.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {mode: 'tags-split',},},});
Value: single
Generates everything into a single file.
For example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {target: 'src/petstore.ts',mock: true,},},});
my-app└── src└── petstore.ts
Here a single file petstore will be created in the src-folder with the specification implementation.
Value: split
Splits implementation, schemas and mocks into different files
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {target: 'src/petstore.ts',mock: true,mode: 'split',},},});
my-app└── src├── petstore.schemas.ts├── petstore.msw.ts└── petstore.ts
Depending on the configuration, there will be multiple files created in src named petstore with a suffix to differentiate them.
- petstore.schemas.ts
- petstore.ts
- petstore.msw.ts
For Angular:
=> petstore.ts is petstore.service.ts
Value: tags
Use this mode to generate one file per tag. A tag is equivalent to an OpenAPI specification tag. Given a pets tag for all pet calls, Orval will generate a file named pets.ts in the target folder
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {target: 'src/petstore.ts',mock: true,mode: 'tags',},},});
my-app└── src├── pets.ts└── petstore.schemas.ts
For Angular:
=> petstore.ts is petstore.service.ts
If the schemas property is not set, only one file per tag will be created, containing the model as well.
Value: tags-split
A combination of the tags and split mode. Orval will generate a folder for every tag in the target folder, and split the files into multiple files in those folders.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {target: 'src/petstore.ts',mock: true,mode: 'tags-split',},},});
my-app└── src├── petstore.schemas.ts└── pets├── petstore.msw.ts└── petstore.ts
Equivalent to the tags mode, if the schemas property is not set, only one file per tag will be created, containing the model as well.
indexFiles
Type: Boolean
Valid values: true or false
Default value: true
Specifies whether an index.ts file is generated during schemas generation.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {schemas: 'src/gen/model',indexFiles: false,},},});
title
Type: String | Function.
Valid values: path or implementation of the function. Only valid for axios and angular implementations.
import { defineConfig } from 'orval';export default defineConfig({output: {override: {title: (title) => `${title}Api`,},},});
baseUrl
Type: String | Object.
Default Value: ''.
Allows you to set the baesUrl used for all API calls. This can either be a constant string or be configured to read from the servers field
in the specification.
Example using constant:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {baseUrl: 'https://api.example.com', // prepend https://api.example.com to all api calls},},});
getBaseUrlFromSpecification
Type: boolean
Valid values: true or false
Default value: true
When set to true, Orval reads the URL from the servers fields in the specification. If a path has defined a servers field,
that URL will be used, otherwise the URL from the specification's root servers field will be used.
If set to false, a constant baseUrl must be set.
Example:
servers:- url: https://api.example.compaths:/pets:servers:- url: https://pets.example.com
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {baseUrl: {getBaseUrlFromSpecification: true,// prepend url defined in specification, in this example: 'https://api.example.com'// for all calls, except for calls to /pets, which will instead use 'https://pets.example.com' as base url.},},},});
variables
Type: Dictionary.
Only valid when getBaseUrlFromSpecification is true.
Used to substitute variables in urls.
If the variable in the specification is an enum, and the provided value in the configuration is not one of the
allowed values, an error will occur when generating.
If a variable that is substituted is not configured, the default value defined in the specification will be used.
Example:
servers:- url: https://{environment}.example.com/v1variables:environment:default: apienum:- api- api.dev- api.staging
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {baseUrl: {getBaseUrlFromSpecification: true,variables: {environment: 'api.dev',},},},},});
index
Type: Number.
Only valid when getBaseUrlFromSpecification is true.
Since the servers field allows for multiple URL to be defined, this options specifies which index of the URL array to pick.
If this is not defined, the first URL will be used.
If the defined index is out of range of the array, the last URL in the array will be selected.
Example:
servers:- url: https://api.example.com/v1- url: https://api.dev.example.com/v1
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {baseUrl: {getBaseUrlFromSpecification: true,index: 1,},},},});
baseUrl
Type: String.
Only valid when getBaseUrlFromSpecification is false.
Behaves the same way as setting the baseUrl as a string directly.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {baseUrl: {getBaseUrlFromSpecification: false,baseUrl: 'https://api.example.com', // The same as setting petstore.output.baseUrl: 'https://api.example.com'},},},});
Gives the same result as:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {baseUrl: 'https://api.example.com',},},});
mock
Type: Boolean | Object | Function.
Default Value: false.
If the value is set to true, Orval will generate mocks using Faker and MSW by default.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {mock: true,},},});
The mock options also accepts a configuration object customizing the generation. If the property is set to true, the default options will be used. The default options are:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {mock: {type: 'msw',delay: 1000,useExamples: false,},},},});
By providing a function, it is possible to extend or create a custom mock generator. See the expected type here.
type
Type: String.
Default Value: msw.
Valid values: msw, cypress (coming soon).
Specifies the type of mocks to be generate.
delay
Type: Number | Function | false.
Default Value: 1000.
Specifies the delay time for the mock. It can either be a fixed number, false or a function that returns a number. Setting delay to false removes the delay call completely.
delayFunctionLazyExecute
Type: boolean.
When set to true, functions that are passed to delay will be executed at runtime rather than when the mocks are generated.
useExamples
Type: Boolean.
When set to true, uses the example/examples fields from the OpenAPI specification as mock values.
generateEachHttpStatus
Type: Boolean.
When set to true, generates mocks for all the HTTP statuses in the responses fields in the OpenAPI specification. By default only the 200 OK response is generated.
baseUrl
Type: String.
Sets the base URL of the mock handlers.
locale
Type: String.
Default Value: en.
Sets the locale for the mock generation. It is used by Faker. See the list of available options here. It should also be strongly typed using defineConfig.
indexMockFiles
Type: Boolean
Default Value: false.
When true, adds an index.msw.ts file which exports arrays with all mock functions.
This is only valid when mode is tags-split.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {mode: 'tags-split',mock: {indexMockFiles: true,},},},});
// index.msw.tsexport { getPetsMock } from './pets/pets.msw';export { getStoresMock } from './stores/stores.msw';// etc...
docs
Type: Boolean | Object.
Default Value: false.
Will generate API docs using TypeDoc. By default the docs will be in Markdown format.
TypeDoc can be configured by passing the options to the docs object or by creating a config file e.g. typedoc.config.mjs in the project root (see the config docs for a full list of supported file names) or by passing a config filename to the configPath option below.
See the TypeDoc configuration documentation for more details.
The docs option can take some properties to customize the generation if you set it to an object. If set to true, the default options will be used.
When no output directory destination is specified in config, the file will be output to the docs directory by default.
For example configuration, see this sample.
configPath
Type: String.
Specifies the TypeDoc config filename. This can be useful if your project already has a TypeDoc config for other docs.
clean
Type: Boolean | String[].
Default Value: false.
Can be used to clean generated files. Provide an array of glob to customize what is deleted.
This will clean all output target and schemas folders.
prettier
Type: Boolean.
Default Value: false.
Can be used to run prettier on the generated files. This requires prettier to be installed globally.
biome
Type: Boolean.
Default Value: false.
When set to true, will apply lint and format of biome to the generated file. The project must have @biomejs/biome in its dependencies.
The automatically generated source code does not comply with some lint rules included in the default ruleset for biome, so please control them in the the project's biome configuration file.
headers
Type: Boolean.
When set to true, enables the generation of the headers
tsconfig
Type: String | Tsconfig.
Should be automatically found.
To use a different configuration, specify the path to the project's tsconfig or directly define the config in this property.
packageJson
Type: String.
Should be automatically found.
Can be used to specify the path to your package.json.
override
Type: Object.
Allows overriding the output to specify mock generation or transforming the API implementation to your project's needs.
transformer
Type: String or Function.
Valid values: path or implementation of the transformer function.
This function is executed for each call when you generate and take in argument a GeneratorVerbOptions and should return a GeneratorVerbOptions
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {transformer: 'src/yourfunction.js',},},},});
mutator
Type: String | Object.
Valid values: path of the mutator function or object with a path and name.
If an object is provided, it is also possible to add a default property to use the default exported function.
This function is executed for each call's execution. It takes all the options passed to the verb as an argument, and should return a Promise with the custom implementation or preferred HTTP client.
Possible arguments:
- The first argument will be an object with the following type.
// based on AxiosRequestConfiginterface RequestConfig {method: 'get' | 'put' | 'patch' | 'post' | 'delete';url: string;params?: any;data?: any;responseType?: string;}
- The second argument is only provided for the Angular client and provides an instance of HttpClient
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {mutator: {path: './api/mutator/custom-instance.ts',name: 'customInstance',// default: true},},},},});
// custom-instance.tsimport Axios, { AxiosRequestConfig } from 'axios';export const AXIOS_INSTANCE = Axios.create({ baseURL: '' });export const customInstance = <T>(config: AxiosRequestConfig): Promise<T> => {const source = Axios.CancelToken.source();const promise = AXIOS_INSTANCE({ ...config, cancelToken: source.token }).then(({ data }) => data,);// @ts-ignorepromise.cancel = () => {source.cancel('Query was cancelled by React Query');};return promise;};// In some case with react-query and swr you want to be able to override the return error type so you can also do it here like thisexport type ErrorType<Error> = AxiosError<Error>;
- If the file has some alias you will also need to define them in the mutator object.
Example:
// custom-instance.tsimport Axios, { AxiosRequestConfig } from 'axios';import config from '@config';export const AXIOS_INSTANCE = Axios.create({ baseURL: '', ...config });export const customInstance = <T>(config: AxiosRequestConfig): Promise<T> => {const source = Axios.CancelToken.source();const promise = AXIOS_INSTANCE({ ...config, cancelToken: source.token }).then(({ data }) => data,);// @ts-ignorepromise.cancel = () => {source.cancel('Query was cancelled by React Query');};return promise;};export type ErrorType<Error> = AxiosError<Error>;
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {mutator: {path: './api/mutator/custom-instance.ts',name: 'customInstance',alias: {'@config': path.resolve(_dirname, './src/config'),},},},},},});
- When using the
react-query,vue-queryorsvelte-queryclient, it is possible to provide a hook.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {mutator: {path: './api/mutator/use-custom-instance.ts',name: 'useCustomInstance',// default: true},},},},});
// use-custom-instance.tsimport Axios, { AxiosRequestConfig } from 'axios';import { useQueryClient } from 'react-query';export const AXIOS_INSTANCE = Axios.create({ baseURL: '' });export const useCustomInstance = <T>(): ((config: AxiosRequestConfig,) => Promise<T>) => {const token = useToken(); // Do what you wantreturn (config: AxiosRequestConfig) => {const source = Axios.CancelToken.source();const promise = AXIOS_INSTANCE({...config,headers: {Authorization: `Bearer ${token}`}cancelToken: source.token,}).then(({ data }) => data);// @ts-ignorepromise.cancel = () => {source.cancel('Query was cancelled by React Query');};return promise;};};export default useCustomInstance;export type ErrorType<Error> = AxiosError<Error>;
- If you use ES modules (
"type": "module"), you can also provide a hook like this
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {mutator: {path: './api/mutator/use-custom-instance.ts',name: 'useCustomInstance',extension: '.js',},},},},});
The generated file will import the mutator with a .js extension.
header
Type: Boolean | Function.
Default Value: true.
Use this property to disable the automatic generation of the file header.
You can provide a function to customize the file header is generated. The function should take an argument of type InfoObject, and should return a string[].
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {header: (info: InfoObject): string[] => [`Generated by Orval 🍺`,`Do not edit manually.`,...(info.title ? [info.title] : []),...(info.description ? [info.description] : []),...(info.version ? [`OpenAPI spec version: ${info.version}`] : []),],},},},});
namingConvention (property keys)
Type: Object.
Change output naming convention generated for property keys.
By default, preserves keys naming convention as is.
If you're looking for file naming convention, see namingConvention.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {...override: {namingConvention: {enum: 'PascalCase',},},},...},});
enum
Type: String.
Changes naming convention for enum keys. All generated enum types supported.
Valid values: : camelCase, PascalCase, snake_case, kebab-case.
same as for file namingConvention.
fetch
Type: Object.
Options related to the generated Fetch client.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {...override: {fetch: {includeHttpResponseReturnType: false,},},},...},});
includeHttpResponseReturnType
Type: Boolean.
Default: true
When using fetch for client or httpClient, the Fetch response type includes HTTP status for easier processing by the application.
To return a defined return type instead of an automatically generated return type, set this value to false.
forceSuccessResponse
Type: Boolean.
Default: false
By default, the Fetch client either returns a success or failure response. This depends on how the specification is set up and what the response code of the request is.
When using fetch along with libraries such as react-query, that expects an error to be thrown on an error response, this default behaviour is not wanted.
By setting this setting to true, Orval will generate code that is typed to always return the successful response type and throw an error when an error response is returned from the request.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {fetch: {forceSuccessResponse: true,},},},},});
export type createPetsResponse200 = {data: Pet;status: 200;};export type createPetsResponseDefault = {data: Error;status: Exclude<HTTPStatusCodes, 200>;};export type createPetsResponseSuccess = createPetsResponse200 & {headers: Headers;};export type createPetsResponseError = createPetsResponseDefault & {headers: Headers;};export const createPets = async (createPetsBody: CreatePetsBody,params: CreatePetsParams,options?: RequestInit,): Promise<createPetsResponseSuccess> => {const res = await fetch(getCreatePetsUrl(params), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },body: JSON.stringify(createPetsBody),});const body = [204, 205, 304].includes(res.status) ? null : await res.text();if (!res.ok) {const err: globalThis.Error & {info?: createPetsResponseError['data'];status?: number;} = new globalThis.Error();const data: createPetsResponseError['data'] = body ? JSON.parse(body) : {};err.info = data;err.status = res.status;throw err;}const data: createPetsResponseSuccess['data'] = body ? JSON.parse(body) : {};return {data,status: res.status,headers: res.headers,} as createPetsResponseSuccess;};
jsonReviver
Type: String or Object
Allows you to provide a reviver function to the fetch client when it parses JSON. It is recommended to use this to revive dates when setting useDates to true
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {fetch: {jsonReviver: {path: './api/mutator/custom-reviver.ts',name: 'customReviver',// default: true},},},},},});
// custom-reviver.tsconst isoDateFormat =/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d*)?(?:[-+]\d{2}:?\d{2}|Z)?$/;export function customReviver(key: string, value: unknown) {if (value && typeof value === 'string' && isoDateFormat.test(value)) {return new Date(value);}return value;}
query
Type: Object.
Overrides the generated query
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {...override: {query: {useQuery: true,useInfinite: true,useInfiniteQueryParam: 'nextId',options: {staleTime: 10000,},signal: true},},},...},});
useQuery
Type: Boolean.
Use to generate useQuery hooks. If the query key isn't provided that's the default hook generated.
useMutation
Type: Boolean.
Use to generate useMutation hooks.
The hook will only be generated if the operation is not a GET operation, and not configured to generate a query.
The operations override will take precedence if both are configured.
useInfinite
Type: Boolean.
Use to generate useInfiniteQuery hooks.
usePrefetch
Type: Boolean.
Use to generate prefetching functions. This may be useful for NextJS SSR or similar prefetching use cases.
Example generated function:
export const prefetchGetCategories = async <TData = Awaited<ReturnType<typeof getCategories>>,TError = ErrorType<unknown>,>(queryClient: QueryClient,options?: {query?: UseQueryOptions<Awaited<ReturnType<typeof getCategories>>,TError,TData,>,request?: SecondParameter<typeof customAxiosInstance>,},): Promise<QueryClient> => {const queryOptions = getGetCategoriesQueryOptions(options);await queryClient.prefetchQuery(queryOptions);return queryClient;};
useInvalidate
Type: Boolean.
Use to generate invalidation functions.
Example generated function:
export const invalidateShowPetById = async (queryClient: QueryClient, petId: string, options?: InvalidateOptions): Promise<QueryClient> => {await queryClient.invalidateQueries({ queryKey: getShowPetByIdQueryKey(petId) }, options);return queryClient;}
useInfiniteQueryParam
Type: String.
Use to automatically add to the request the query param provided by the useInfiniteQuery when you use getFetchMore function.
options (deprecated use queryOptions instead)
Type: Object.
Use to override the query config. Check available options here
queryKey
Type: String | Object.
Valid values: path of the queryKey function or object with a path and name.
If an object is provided, it is also possible to add a default property to use the default exported function.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {query: {queryKey: {path: './api/query/custom-query-key.ts',name: 'customQueryKeyFn',// default: true},},},},},});
queryOptions
Type: String | Object.
Valid values: path of the queryOptions function or object with a path and name.
If an object is provided, it is also possible to add a default property to use the default exported function.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {query: {queryOptions: {path: './api/query/custom-query-options.ts',name: 'customQueryOptionsFn',// default: true},},},},},});
mutationOptions
Type: String | Object.
Valid values: path of the mutationOptions function or object with a path and name.
If an object is provided, it is also possible to add a default property to use the default exported function.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {query: {mutationOptions: {path: './api/mutator/custom-mutator-options.ts',name: 'useCustomMutatorOptions',// default: true},},},},},});
// custom-mutator-options.tstype OptionsWithMutationFn<TData = unknown,TError = Error,TVariables = void,TContext = unknown,> = UseMutationOptions<T, TError, TData, TContext> &Required<Pick<UseMutationOptions<T, TError, TData, TContext>, 'mutationFn'>>;export const useCustomMutatorOptions = <TData = unknown,TError = Error,TVariables = void,TContext = unknown,>(options: OptionsWithMutationFn<T, TError, TData, TContext>,): OptionsWithMutationFn<T, TError, TData, TContext> => {const queryClient = useQueryClient();if (options.mutationKey?.[0] === 'petDestroy') {// Note: `options.mutationKey?.[0]` is untyped.options.onSuccess = (_data, variables, _context) => {// Note: `variables` is untyped.options.onSuccess?.(data, variables, context);// Note: `queryKey` is hardcoded, can't use `getGetPetQueryKey()` as it would introduce circular dependencies.queryClient.invalidateQueries({queryKey: ['api', 'v2', 'pet', variables.id],});};}// TODO: add more ifs for each mutation.return options;};
signal
Type: Boolean.
Use to remove the generation of the abort signal provided by query
shouldExportMutatorHooks
Type: Boolean.
Default Value: true.
Use to stop the export of mutator hooks. Useful if you want to rely solely on useQuery, useSuspenseQuery, etc.
shouldExportQueryKey
Type: Boolean.
Default Value: true.
Use to stop the export of query keys.
shouldSplitQueryKey
Type: Boolean.
Default Value: false.
Use to make Orval generate query keys as arrays instead of strings.
useOperationIdAsQueryKey
Type: Boolean.
Default Value: false.
Use to generate query keys using the OpenAPI operation ID instead of the route path. This provides more stable and semantic query keys that don't change when route paths are modified.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {query: {useOperationIdAsQueryKey: true,},},},},});
Generated code comparison:
Default behavior (useOperationIdAsQueryKey: false):
const getPetByIdQueryKey = (petId: string) => {return [`/pets/${petId}`] as const;};
With useOperationIdAsQueryKey: true:
const getPetByIdQueryKey = (petId: string) => {return ['getPetById', petId] as const;};
version
Type: number.
Default Value: Detect from package json.
Use to specify a version for the generated hooks. This is useful if you want to force a version for the hooks.
angular
Type: Object.
Allows specifying options for the Angular client
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {...override: {angular: {provideIn: 'any',},},},...},});
provideIn
Type: Boolean | String.
Valid values: true, false, 'root', 'any', ''.
Default Value: 'root'.
Can be used to set the value of providedIn on the generated Angular services. If false, no providedIn will be set. If true or not specified, it will fall back to the default value: root.
swr
Type: Object.
Options for generating the swr client. It is also possible to extend the generated functions.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {...override: {swr: {useInfinite: true,},},},...},});
useInfinite
Type: Boolean.
Use to generate a useSWRInfinite custom hook.
useSWRMutationForGet
Type: Boolean.
Use to generate a useSWRMutation custom hook for get request.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {swr: {swrOptions: {useSWRMutationForGet: true,},},},},},});
swrOptions
Type: Object.
Use to override the useSwr options. See available options here
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {swr: {swrOptions: {dedupingInterval: 10000,},},},},},});
swrMutationOptions
Type: Object.
Use to override the useSWRMutation options. See available options here
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {swr: {swrMutationOptions: {revalidate: true,},},},},},});
swrInfiniteOptions
Type: Object.
Use to override the useSWRInfinite options. See available options here
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {swr: {swrInfiniteOptions: {initialSize: 10,},},},},},});
zod
Type: Object.
Options for generating the Zod client
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {...override: {zod: {strict: {response: true,query: true,param: true,header: true,body: true},coerce: {response: true,query: true,param: true,header: true,body: true},},},},...},});
strict
Type: Object.
Default Value: false.
Use to set the strict mode for the Zod schema. If set to true, the schema will be generated with strict mode.
generate
Type: Object.
Use to define the Zod schemas to be generated.
example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {...override: {zod: {generate: {param: true,body: true,response: false,query: true,header: true,}},},},...},});
In the above example, response body validations are not generated
coerce
Type: Object.
Use to configure coercion for the Zod schema. If set to true, the schema will be generated with the coerce on all possible types.
If an array of coerce types are provided, coercion is only generated for the specified types.
example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {...override: {zod: {coerce: {response: [ 'boolean'],query: ['string', 'number', 'boolean', 'bigint', 'date'],}},},},...},});
preprocess
Type: Object.
Use to add a preprocess function to a Zod schema. Provide a custom mutator to preprocess the data before it is validated.
example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {...override: {zod: {preprocess: {response: {name: 'stripNill',path: './src/mutators.ts',},},},},},...},});
generateEachHttpStatus
Type: Boolean.
Allows generating mocks for all the HTTP statuses in the responses fields of the provided OpenAPI specification. By default only the 200 OK response is generated.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {...override: {zod: {generateEachHttpStatus: true,},},},...},});
dateTimeOptions
Type: Object.
Default Value: {}.
Use to set options for Zod datetime fields. These options are passed directly to zod datetime validation.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {zod: {dateTimeOptions: {local: true,offset: true,precision: 3,},},},},},});
Read more about datetimes in the Zod documentation.
timeOptions
Type: Object.
Default Value: {}.
Use to set options for Zod time fields. These options are passed directly to Zod time validation.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {zod: {timeOptions: {precision: -1,},},},},},});
Read more about times in the Zod documentation.
mock
Type: Object.
Allows overriding the generated mock.
properties
Type: Object | Function.
Use this to override the generated mock per property. Properties can either be a function that receives the specification as an argument and returns an object, or it can be a static object.
Each key of this object can be a regex or the path of the property to override. The value can either be a function returning a value, or a static value. If a function is provided, it will be executed at runtime.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {mock: {properties: {'/tag|name/': 'jon', // Matches every property named 'tag' or 'name', including nested ones'/.*.user.id/': faker.string.uuid(), // Matches every property named 'id', inside an object named 'user', including nested onesemail: () => faker.internet.email(), // Matches only the property 'email''user.id': () => faker.string.uuid(), // Matches only the full path 'user.id'},},},},},});
format
Type: Object.
Allows providing values for format in the OpenAPI specification.
For example, if format: email is on a property in the OpenAPI specification, Orval will automatically generate a random email. See the default available format here.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {mock: {format: {email: () => faker.internet.email(),iban: () => faker.finance.iban(),},},},},},});
required
Type: Boolean.
Sets every property to be required.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {mock: {required: true,},},},},});
delay
Type: Number | Function | false.
Sets the delay time for the mock. It can either be a fixed number, false or a function that returns a number. Setting delay to false removes the delay call completely.
Default Value: 1000
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {mock: {delay: 0,},},},},});
delayFunctionLazyExecute
Type: boolean.
When set to true, the function passed to delay will be executed at runtime rather than when the mocks are generated.
generateEachHttpStatus
Type: Boolean.
When set to true, Orval will generate mocks for all the HTTP statuses in the responses fields of the provided OpenAPI specification.
arrayMin
Type: Number.
Sets the default minimum length of generated arrays for properties that specify multiple items. Used if minItems is not defined for the property. (Default is 1)
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {mock: {arrayMin: 5,},},},},});
arrayMax
Type: Number.
Sets the default maximum length of generated arrays for properties that specify multiple items. Used if maxItems is not defined for the property. (Default is 10)
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {mock: {arrayMax: 15,},},},},});
stringMin
Type: Number.
Sets the default minimum length of generated strings. Used if minLength is not defined for the property. (Default is 10)
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {mock: {stringMin: 5,},},},},});
stringMax
Type: Number.
Sets the default maximum length of generated strings. Used if maxLength is not defined for the property. (Default is 20)
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {mock: {stringMax: 15,},},},},});
numberMin
Type: Number.
Sets the default minimum value of generated numbers. Used if minimum is not defined for the property.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {mock: {numberMin: 5,},},},},});
numberMax
Type: Number.
Sets the default maximum value of generated numbers. Used if maximum is not defined for the property.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {mock: {numberMax: 15,},},},},});
fractionDigits
Type: Number.
Sets number of decimals displayed in floating-point numbers. (Default is 2)
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {mock: {fractionDigits: 1,},},},},});
useExamples
An extension of the global mock option. If set to true, the mock generator will use the example property of the specification to generate the mock. If the example property is not set, the mock generator will fall back to the default behavior. Will override the global option.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {mock: {useExamples: true,},},},},});
baseUrl
Type: String.
Sets the base URL in the mock handlers. Will override the global option.
hono
Type: Object
Overrides the generated hono files
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {hono: {handlers: 'src/handlers',validatorOutputPath: 'src/validator.ts',compositeRoute: 'src/routes.ts',},},},},});
handlers
Type: String.
Changes the output path for the hono handlers.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {hono: {handlers: 'src/handlers',},},},},});
The files will be generated as below:
src/├── handlers│ ├── createPets.ts│ ├── listPets.ts│ ├── showPetById.ts│ └── updatePets.ts├── index.ts├── mutators.ts├── petstore.context.ts├── petstore.schemas.ts├── petstore.ts├── petstore.validator.ts└── petstore.zod.ts
validatorOutputPath
Type: String.
Changes the validator output path
compositeRoute
Type: String.
When a string is provided, Orval will generate a single composite route file, containing all routes to the provided path.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {hono: {compositeRoute: 'src/routes.ts',},},},},});
The files will be generated as below:
src/├── endpoints│ ├── pets│ │ ├── pets.context.ts│ │ ├── pets.handlers.ts│ │ └── pets.zod.ts│ └── validator.ts├── routes.ts└── schemas├── pet.ts└── pets.ts
components
Type: Object.
Allows overriding the generated model names by adding a suffix to each name.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {components: {schemas: {suffix: 'DTO',},responses: {suffix: 'Response',},parameters: {suffix: 'Params',},requestBodies: {suffix: 'Bodies',},},},},},});
operations
Type: Object.
Allows overriding the generated mocks by operationId.
Each key of the operations object should be an operationId from the schema, and take as value an object.
The value object can take the same properties as the override property (mutator,query,transformer,mock).
The mock object allows an additional property; the data property. This property can take a function or the value directly. The function will be executed at runtime.
import { faker } from '@faker-js/faker';import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {operations: {listPets: {transformer: 'src/yourfunction.js',mutator: 'src/response-type.js',mock: {properties: () => {return {id: () => faker.number.int({ min: 1, max: 99999 }),};},},},showPetById: {mock: {data: () => ({id: faker.number.int({ min: 1, max: 99 }),name: faker.person.firstName(),tag: faker.helpers.arrayElement([faker.word.sample(),undefined,]),}),},},},},},},});
tags
Type: Object.
Equivalent to override.operations, except overrides are done by tags
operationName
Type: Function.
Type signature:
(operation: OperationObject, route: string, verb: Verbs) => string;
Function to override the generated operation names.
requestOptions
Type: Object | Boolean.
Use this property to provide a config to the HTTP client or completely remove the request options property from the generated files.
formData
Type: Boolean | String | Object.
Valid values: path of the formData function or object with a path and name.
This allows defining how the names of form entries are handled regarding arrays.
Use this property to disable the auto generation of form data when using multipart
If an object is provided, it is also possible to add a default property to use the default exported function.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {formData: {path: './api/mutator/custom-form-data-fn.ts',name: 'customFormDataFn',// default: true},},},},});
// type signatureexport const customFormDataFn = <Body>(body: Body): FormData => {// do your implementation to transform it to FormDatareturn FormData;};
mutator
Type: String | Object
Equivalent to providing the mutator directly to the formData property, while also allowing the use of the arrayHandling property.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {formData: {mutator: {path: './api/mutator/custom-form-data-fn.ts',name: 'customFormDataFn',},},},},},});
arrayHandling
Type: serialize | serialize-with-brackets | explode
Default Value: serialize
Specifies how FormData generation handles arrays.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {formData: {mutator: {path: './api/mutator/custom-form-data-fn.ts',name: 'customFormDataFn',},arrayHandling: 'serialize-with-brackets',},},},},});
For all of the following examples, this specification is used:
components:schemas:Pet:type: objectproperties:name:type: stringage:type: numberrelatives:type: arrayitems:type: objectproperties:name:type: stringcolors:type: arrayitems:type: stringenum:- white- black- green
Setting the value to serialize results in the following generated code:
const formData = new FormData();if (pet.name !== undefined) {formData.append(`name`, pet.name);}if (pet.age !== undefined) {formData.append(`age`, pet.age.toString());}if (pet.relatives !== undefined) {pet.relatives.forEach((value) =>formData.append(`relatives`, JSON.stringify(value)),);}
Setting the value to serialize-with-brackets results in the following generated code:
const formData = new FormData();if (pet.name !== undefined) {formData.append(`name`, pet.name);}if (pet.age !== undefined) {formData.append(`age`, pet.age.toString());}if (pet.relatives !== undefined) {pet.relatives.forEach((value) =>formData.append(`relatives[]`, JSON.stringify(value)),);}
Setting the value to explode results in the following generated code:
const formData = new FormData();if (pet.name !== undefined) {formData.append(`name`, pet.name);}if (pet.age !== undefined) {formData.append(`age`, pet.age.toString());}if (pet.relatives !== undefined) {pet.relatives.forEach((value, index) => {if (value.name !== undefined) {formData.append(`relatives[${index}].name`, value.name);}if (value.colors !== undefined) {value.colors.forEach((value, index1) =>formData.append(`relatives[${index}].colors[${index1}]`, value),);}});}
formUrlEncoded
Type: Boolean | String | Object.
Valid values: path of the formUrlEncoded function or object with a path and name.
Use this property to disable the auto generation of form url encoded
If an object is provided, it is also possible to add a default property to use the default exported function.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {formUrlEncoded: {path: './api/mutator/custom-form-url-encoded-fn.ts',name: 'customFormUrlEncodedFn',// default: true},},},},});
// type signatureexport const customFormUrlEncodedFn = <Body>(body: Body): URLSearchParams => {// do your implementation to transform it to FormDatareturn URLSearchParams;};
paramsSerializer
Type: String | Object.
IMPORTANT: This is only valid when using Axios or Angular.
Valid values: path of the paramsSerializer function or object with a path and name.
Use this property to add a custom parameter serializer to all requests that use query parameters.
If an object is provided, it is also possible to add a default property to use the default exported function.
If this is not specified, params are serialized as per Axios default.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {paramsSerializer: {path: './api/mutator/custom-params-serializer-fn.ts',name: 'customParamsSerializerFn',// default: true},},},},});
// type signatureexport const customParamsSerializerFn = (params: Record<string, any>,): string => {// do your implementation to transform the paramsreturn params;};
paramsSerializerOptions
Type: Object
IMPORTANT: This is only valid when using Axios or Angular.
Use this property to specify how parameters are serialized. This is only taken into account when paramsSerializer is not defined.
Currently, qs is the only available option. Read more about qs and its settings here.
If this is not specified, parameters are serialized as per Axios default.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {paramsSerializerOptions: {qs: {arrayFormat: 'repeat',},},},},},});
useDates
Type: Boolean
Valid values: true or false. Defaults to false.
Use this property to convert OpenAPI date or datetime to JavaScript Date objects instead of string.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {useDates: true,},},},});
Note: You must provide an Axios converter to convert the serialised date strings to Date objects. This option only affects the TypeScript definition. If using fetch as your client, you can provide a jsonReviver override function.
You can choose to use any Date library you want like Moment, Luxon, or native JS Dates.
// type signatureconst client = axios.create({baseURL: '',});client.interceptors.response.use((originalResponse) => {handleDates(originalResponse.data);return originalResponse;});export default client;const isoDateFormat =/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d*)?(?:[-+]\d{2}:?\d{2}|Z)?$/;function isIsoDateString(value: any): boolean {return value && typeof value === 'string' && isoDateFormat.test(value);}export function handleDates(body: any) {if (body === null || body === undefined || typeof body !== 'object')return body;for (const key of Object.keys(body)) {const value = body[key];if (isIsoDateString(value)) {body[key] = new Date(value); // default JS conversion// body[key] = parseISO(value); // date-fns conversion// body[key] = luxon.DateTime.fromISO(value); // Luxon conversion// body[key] = moment(value).toDate(); // Moment.js conversion} else if (typeof value === 'object') {handleDates(value);}}}
Note: If you are using fetch as your client and useDates is set to true, query parameters of type Date will be stringified using toISOString()
useBigInt
Type: Boolean
Valid values: true or false. Defaults to false.
Use this property to convert OpenAPI int64 and uint64 format to JavaScript BigInt objects instead of number.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {useBigInt: true,},},},});
useNamedParameters
Type: Boolean.
Default Value: false.
Generates the operation interfaces with named path parameters instead of individual arguments for each path parameter.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {useNamedParameters: true,},},},});
useTypeOverInterfaces
Type: Boolean
Valid values: true or false. Defaults to false.
Use this property to use TypeScript type instead of interface.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {useTypeOverInterfaces: true,},},},});
useDeprecatedOperations
Type: Boolean
Valid values: true or false. Defaults to true.
Use this property to include/exclude generating any operation marked "deprecated": true in OpenAPI.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {useDeprecatedOperations: false,},},},});
contentType
Type: Object
Use this property to include or exclude content types
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {contentType: {include: ['application/json'],exclude: ['application/xml'],},},},},});
enumGenerationType
Type: const | enum | union
Default Value: const.
This is used to specify how enums are generated. const generates a const object, enum generates a native enum and union generates a simple union type.
To change the name of the generated enum keys, you can extend your OpenAPI schema with x-enumNames. Read more here.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {enumGenerationType: 'const',},},},});
Result when enumGenerationType is const:
export type Example = (typeof Example)[keyof typeof Example];// eslint-disable-next-line @typescript-eslint/no-redeclareexport const Example = {foo: 'foo',bar: 'bar',baz: 'baz',} as const;
Result when enumGenerationType is enum:
export enum Example {foo = 'foo',bar = 'bar',baz = 'baz',}
Result when enumGenerationType is union:
export const Example = 'foo' | 'bar' | 'baz';
suppressReadonlyModifier
Type: Boolean
Valid Values: true or false.
Default Value: false.
When the readonly field is specified in OpenAPI, specify readonly in the type and interface fields output from the schema.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {suppressReadonlyModifier: true,},},},});
jsDoc
filter
Type: Object.
A configuration object that allows you to customize JSDoc generation by optionally providing a filter function that transforms schema entries into key-value pairs.
Example:
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {override: {jsDoc: {filter: (schema) => {const allowlist = ['type','format','maxLength','minLength','description','minimum','maximum','exclusiveMinimum','exclusiveMaximum','pattern','nullable','enum',];return Object.entries(schema || {}).filter(([key]) => allowlist.includes(key)).map(([key, value]) => {return {key,value,};}).sort((a, b) => {return a.key.length - b.key.length;});},},},},},});
Input:
components:schemas:Pet:type: objectrequired:- id- nameoneOf:- $ref: '#/components/schemas/Dog'- $ref: '#/components/schemas/Cat'properties:'@id':type: stringformat: iri-referenceid:type: integerformat: int64name:type: stringtag:type: stringemail:type: stringformat: emailcallingCode:type: stringenum: ['+33', '+420', '+33'] # intentional duplicated valuecountry:type: stringenum: ["People's Republic of China", 'Uruguay']
Result:
export interface Pet {/*** @type integer* @format int64*/id: number;/*** @type string* @maxLength 0* @minLength 40* @description Name of pet*/name: string;/*** @type integer* @format int32* @minimum 0* @maximum 30* @exclusiveMinimum true* @exclusiveMaximum true*/age?: number;/*** @type string* @pattern ^\\d{3}-\\d{2}-\\d{4}$* @nullable true*/tag?: string | null;/*** @type string* @format email*/email?: string;/*** @type string* @enum +33,+420,+33*/callingCode?: PetCallingCode;/*** @type string* @enum People's Republic of China,Uruguay*/country?: PetCountry;}
allParamsOptional
Type: Boolean
Valid Values: true or false.
Default Value: false.
Applies to all clients, but is usually just relevant for Tanstack Query.
Use this property to make all parameters optional except the path parameter. This is useful to take advantage of Orval's auto-enable feature for Tanstack Query, see https://github.com/orval-labs/orval/pull/894
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {allParamsOptional: true,},},});
urlEncodeParameters
Type: Boolean
Valid values: true or false. Defaults to false. Note: this only works for Tanstack Query clients and fetch httpClients for now.
Use this property to enable URL encoding of path/query parameters. This is highly recommended, and will probably become the default behaviour in the future, see https://github.com/orval-labs/orval/pull/895
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {urlEncodeParameters: true,},},});
optionsParamRequired
Type: Boolean
Valid Values: true or false.
Default Value: false.
Use this property to make the second options parameter required (such as when using a custom Axios instance)
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {optionsParamRequired: true,},},});
propertySortOrder
Type: Alphabetical | Specification
Default Value: Specification
Specifies how properties in the models are sorted, either alphabetically or in the order they appear in the specification.
import { defineConfig } from 'orval';export default defineConfig({petstore: {output: {propertySortOrder: 'Alphabetical',},},});