The fetch
API has the advantage of reducing the bundle size of the application compared to using Axios
. It can also act as an http client
in server-side frameworks and edge computing runtimes such as Cloudflare
, Vercel Edge
and Deno
.
You should have an OpenAPI
specification and an Orval
config where you define the mode as 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',},},});
Checkout the orval config reference to see all available options.
Like the following example from 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 };};
The fetch
client will generate an implementation file with following per path in your OpenAPI
Specification.
fetch
functionfetch
API.Checkout here the full example
You can add a custom fetch
function to your config.
module.exports = {petstore: {output: {...override: {mutator: {path: './custom-fetch.ts',name: 'customFetch',},},}...},};
And, you prepare like the sample implementation
Then, you can generate a fetch
client that calls the customFetch
function like bellow:
export const listPets = async (params?: ListPetsParams,options?: RequestInit,): Promise<listPetsResponse> => {return customFetch<Promise<listPetsResponse>>(getListPetsUrl(params), {...options,method: 'GET',});};