Skip to main content

Fetch

The Fetch API is a native browser API, and thus doesn't require bundling additional dependencies, as is the case with Axios. It can also act as an HTTP client in server-side frameworks and edge computing runtimes such as Cloudflare, Vercel Edge and Deno.

Start by providing an OpenAPI specification and an Orval config where you define the mode as fetch.

Example with Fetch

import { defineConfig } from 'orval';
export default defineConfig({
petstore: {
output: {
mode: 'tags-split',
target: 'app/gen/petstore.ts',
schemas: 'app/gen/models',
client: 'fetch',
baseUrl: 'http://localhost:3000',
mock: true,
},
input: {
target: './petstore.yaml',
},
},
});

Navigate to the Orval config reference to see all available options.

The following example shows autogenerated functions based on this OpenAPI Specification:

/**
* @summary List all pets
*/
export type listPetsResponse = {
data: Pets;
status: number;
};
export const getListPetsUrl = (params?: ListPetsParams) => {
const normalizedParams = new URLSearchParams();
Object.entries(params || {}).forEach(([key, value]) => {
if (value === null) {
normalizedParams.append(key, 'null');
} else if (value !== undefined) {
normalizedParams.append(key, value.toString());
}
});
return `http://localhost:3000/pets?${normalizedParams.toString()}`;
};
export const listPets = async (
params?: ListPetsParams,
options?: RequestInit,
): Promise<listPetsResponse> => {
const res = await fetch(getListPetsUrl(params), {
...options,
method: 'GET',
});
const data = await res.json();
return { status: res.status, data };
};

Setting the client parameter to fetch will generate an implementation file with the following for each path in the OpenAPI Specification.

  1. A response type for the Fetch function
  2. A function to generate request URL including query parameters and path parameters
  3. A function that calls the Fetch API.

Checkout here the full example

Custom Function

It is possible to add a custom fetch function to the Orval config.

module.exports = {
petstore: {
output: {
...
override: {
mutator: {
path: './custom-fetch.ts',
name: 'customFetch',
},
},
}
...
},
};

Copy the sample implementation from GitHub and modify the function as needed. The generated functions will now call the customFetch function:

export const listPets = async (
params?: ListPetsParams,
options?: RequestInit,
): Promise<listPetsResponse> => {
return customFetch<Promise<listPetsResponse>>(getListPetsUrl(params), {
...options,
method: 'GET',
});
};
Was this page helpful?