OrvalOrval

Fetch

Generate Fetch API clients from OpenAPI

The Fetch API is a native browser API requiring no additional dependencies. It also works in server-side frameworks and edge runtimes like Cloudflare Workers, Vercel Edge, and Deno.

Configuration

Set the client option to fetch:

orval.config.ts
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',
    },
  },
});

Generated Output

Orval generates three things for each endpoint:

1. Response Type

export type listPetsResponse = {
  data: Pets;
  status: number;
};

2. URL Generator

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()}`;
};

3. Fetch Function

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 };
};

Custom Fetch Function

Add a custom fetch implementation via mutator:

orval.config.ts
import { defineConfig } from 'orval';

export default defineConfig({
  petstore: {
    output: {
      // ...
      override: {
        mutator: {
          path: './custom-fetch.ts',
          name: 'customFetch',
        },
      },
    },
    // ...
  },
});

The generated functions will use your custom implementation:

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

Full Example

See the Next.js with Fetch example on GitHub.

On this page