---
title: "Faker v10 Plugin"
description: "Generate Faker v10 fake data from OpenAPI with the Faker plugin for openapi-ts. Fully compatible with validators, transformers, and all core features."
url: "https://heyapi.dev/docs/openapi/typescript/plugins/faker"
---

In Progress[Track progress](https://github.com/hey-api/hey-api/issues/1485)·[Contribute](https://heyapi.dev/docs/openapi/typescript/community/contributing)[👍129](https://github.com/hey-api/hey-api/issues/1485)

### About

[Section titled “About”](#about)

[Faker](https://fakerjs.dev) is a popular library that generates fake (but reasonable) data that can be used for things such as unit testing, performance testing, building demos, and working without a completed backend.

The Faker plugin for Hey API generates factory functions from your OpenAPI spec that return realistic mock data using `@faker-js/faker`.

### Collaborators

[Section titled “Collaborators”](#collaborators)

* [![Malcolm Kee](https://heyapi.dev/_astro/malcolm-kee_2fbFLx.webp)Malcolm Kee](https://github.com/malcolm-kee)

## Features

[Section titled “Features”](#features)

* Faker v9 and v10 support
* seamless integration with `@hey-api/openapi-ts` ecosystem
* factory functions for reusable schema definitions, operation requests, and operation responses
* smart property name inference for realistic data (e.g. `email` → `faker.internet.email()`)
* constraint and format awareness (min/max, string formats, array bounds)
* optional property and default value handling
* dependency injection for custom faker instances (locale, seed)
* minimal learning curve thanks to extending the underlying technology

## Installation

[Section titled “Installation”](#installation)

In your [configuration](https://heyapi.dev/docs/openapi/typescript/get-started), add `@faker-js/faker` to your plugins and you’ll be ready to generate faker factories. 🎉

openapi-ts.config.ts

```js
export default {
  input: 'hey-api/backend', // sign up at app.heyapi.dev
  output: 'src/client',
  plugins: [
    // ...other plugins
    '@faker-js/faker',
  ],
};
```

## Output

[Section titled “Output”](#output)

The Faker plugin will generate the following artifacts, depending on the input specification.

## Definitions

[Section titled “Definitions”](#definitions)

A factory function is generated for every reusable definition from your input.

* example

  faker.gen.ts

  ```ts
  import { faker, type Faker } from '@faker-js/faker';


  import type { Bar, Foo } from '../types.gen';


  export const fakeFoo = (options?: Options): Foo => ({
    name: ensureFaker(options).string.sample(),
    age: ensureFaker(options).number.int({ min: 1, max: 120 }),
  });


  export const fakeBar = (options?: Options): Bar =>
    ensureFaker(options).helpers.arrayElement(['baz', 'qux']);
  ```

* config

  openapi-ts.config.ts

  ```js
  export default {
    input: 'hey-api/backend', // sign up at app.heyapi.dev
    output: 'src/client',
    plugins: [
      // ...other plugins
      {
        name: '@faker-js/faker',
        definitions: true,
      },
    ],
  };
  ```

You can customize the naming and casing pattern for `definitions` factories using the `.name` and `.case` options.

## Requests

[Section titled “Requests”](#requests)

A single factory function is generated per operation for request data. It combines the request body, path parameters, query parameters, and headers into one object. Only keys with actual data are included.

* example

  faker.gen.ts

  ```ts
  // body + path + query combined into one factory
  export const fakeUpdatePetRequest = (options?: Options): Omit<UpdatePetData, 'url'> => {
    const f = options?.faker ?? faker;
    return {
      body: {
        name: f.string.sample(),
        tag: fakeTag(options),
      },
      path: {
        id: f.string.uuid(),
      },
      query: {
        dryRun: f.datatype.boolean(),
      },
    };
  };


  // body only
  export const fakeCreatePetRequest = (options?: Options): Omit<CreatePetData, 'url'> => {
    const f = options?.faker ?? faker;
    return {
      body: {
        name: f.string.sample(),
      },
    };
  };
  ```

* config

  openapi-ts.config.ts

  ```js
  export default {
    input: 'hey-api/backend', // sign up at app.heyapi.dev
    output: 'src/client',
    plugins: [
      // ...other plugins
      {
        name: '@faker-js/faker',
        requests: true,
      },
    ],
  };
  ```

You can customize the naming and casing pattern for `requests` factories using the `.name` and `.case` options.

## Responses

[Section titled “Responses”](#responses)

A factory function is generated for operation responses. When an operation has a single success response, the factory is unsuffixed. When multiple responses exist, each factory is suffixed with the status code.

* example

  faker.gen.ts

  ```ts
  // single success response — unsuffixed
  export const fakeCreatePetResponse = (options?: Options): CreatePetResponse => fakePet(options);


  // multiple responses — suffixed with status code
  export const fakeGetPetResponse200 = (options?: Options): GetPetResponses[200] => fakePet(options);


  export const fakeGetPetResponse404 = (options?: Options): GetPetErrors[404] => fakeError(options);
  ```

* config

  openapi-ts.config.ts

  ```js
  export default {
    input: 'hey-api/backend', // sign up at app.heyapi.dev
    output: 'src/client',
    plugins: [
      // ...other plugins
      {
        name: '@faker-js/faker',
        responses: true,
      },
    ],
  };
  ```

You can customize the naming and casing pattern for `responses` factories using the `.name` and `.case` options.

## Smart Inference

[Section titled “Smart Inference”](#smart-inference)

The plugin infers semantically appropriate faker methods from property names, producing more realistic mock data without requiring explicit schema formats or annotations.

```ts
// property name "email" → faker.internet.email()
// property name "firstName" → faker.person.firstName()
// property name "city" → faker.location.city()
// property name "id" → faker.string.uuid()
// property name "age" → faker.number.int({ min: 1, max: 120 })
```

Ancestor context is also used for disambiguation. For example, `name` under a `User` schema produces `faker.person.fullName()`, while `name` under a `Company` schema produces `faker.company.name()`.

Explicit schema annotations (format, pattern, constraints) always take priority over name-based inference.

### Name Rules

[Section titled “Name Rules”](#name-rules)

You can extend or override the built-in name inference with custom `nameRules`. Rules are defined per schema type (`string` or `number`) and map property names to specific faker methods.

* example

  faker.gen.ts

  ```ts
  export const fakeError = (options?: Options): Error => {
    const f = options?.faker ?? faker;
    return {
      code: f.number.int(),
      message: f.word.words({ count: 4 }),
    };
  };


  export const fakeDocument = (options?: Options): Document => {
    const f = options?.faker ?? faker;
    return {
      id: f.database.mongodbObjectId(),
      _id: f.database.mongodbObjectId(),
    };
  };
  ```

* config

  openapi-ts.config.ts

  ```js
  export default {
    input: 'hey-api/backend', // sign up at app.heyapi.dev
    output: 'src/client',
    plugins: [
      // ...other plugins
      {
        name: '@faker-js/faker',
        nameRules: {
          string: {
            // compound rule: "message" inside an "error" schema
            'error.message': {
              fakerPath: ['word', 'words'],
              defaultArgs: { count: 4 },
            },
            // suffix rule: any property ending with "id"
            id: {
              fakerPath: ['database', 'mongodbObjectId'],
              suffixMatch: true,
            },
          },
        },
      },
    ],
  };
  ```

Each rule requires a `fakerPath` — a tuple of `[module, method]` corresponding to a faker method (e.g. `['database', 'mongodbObjectId']` for `faker.database.mongodbObjectId()`). You can optionally provide `defaultArgs` to pass default arguments to the faker method.

**Matching strategies:**

* **Exact match** — `'email'` matches a property named `email`
* **Compound match** — `'error.message'` matches a property named `message` inside an ancestor named `error`
* **Suffix match** — `'id'` with `suffixMatch: true` matches any property ending with `id` (e.g. `userId`, `_id`)

User-provided rules take priority over built-in rules. Property names are normalized (lowercased, separators removed) before matching.

## Formats and Constraints

[Section titled “Formats and Constraints”](#formats-and-constraints)

The plugin respects OpenAPI schema formats and constraints to generate appropriately bounded data.

**String formats:**

* `email` → `faker.internet.email()`
* `date-time` → `faker.date.recent().toISOString()`
* `date` → `faker.date.recent().toISOString().slice(0, 10)`
* `uuid` → `faker.string.uuid()`
* `uri` / `url` → `faker.internet.url()`
* `ipv4` → `faker.internet.ipv4()`
* `ipv6` → `faker.internet.ipv6()`
* `pattern` → `faker.helpers.fromRegExp(pattern)`

**Numeric constraints:**

* `minimum` / `maximum` → `faker.number.int({ min, max })`
* `exclusiveMinimum` / `exclusiveMaximum` → adjusted bounds

**String constraints:**

* `minLength` / `maxLength` → `faker.string.alpha({ length: { min, max } })`

**Array constraints:**

* `minItems` / `maxItems` → controls count in `faker.helpers.multiple()`

## Optional Properties

[Section titled “Optional Properties”](#optional-properties)

Required properties are always included. Optional properties are controlled by the `includeOptional` option at runtime.

```ts
const user = fakeFoo(); // includes optional properties by default
const user = fakeFoo({ includeOptional: false }); // excludes optional properties
const user = fakeFoo({ includeOptional: 0.5 }); // 50% probability per optional property
```

## Default Values

[Section titled “Default Values”](#default-values)

When a schema defines default values, you can control whether to use them instead of generating fake data via the `useDefault` option.

```ts
const data = fakeFoo(); // always generates fake data
const data = fakeFoo({ useDefault: true }); // uses schema defaults when available
const data = fakeFoo({ useDefault: 0.5 }); // 50% probability of using defaults
```

## Circular References

[Section titled “Circular References”](#circular-references)

Schemas with circular references are automatically detected, whether self-referencing (a schema that refers to itself) or mutually recursive (two or more schemas that refer to each other). The generated factories use a depth counter to prevent infinite recursion, returning empty arrays or omitting optional properties once the limit is reached.

The maximum depth defaults to `10` and can be configured via the `maxCallDepth` option.

## Locale

[Section titled “Locale”](#locale)

You can configure the locale for generated faker factories. When set, the generated code imports the faker instance from the locale-specific build of `@faker-js/faker`.

* example

  faker.gen.ts

  ```ts
  import { faker } from '@faker-js/faker/locale/de';
  import type { Faker } from '@faker-js/faker';
  ```

* config

  openapi-ts.config.ts

  ```js
  export default {
    input: 'hey-api/backend', // sign up at app.heyapi.dev
    output: 'src/client',
    plugins: [
      // ...other plugins
      {
        name: '@faker-js/faker',
        locale: 'de',
      },
    ],
  };
  ```

See the [Faker localization guide](https://fakerjs.dev/guide/localization) for available locales.

## Deterministic Results

[Section titled “Deterministic Results”](#deterministic-results)

For snapshot testing or reproducible output, you can seed the faker instance and fix the reference date to ensure deterministic results.

```ts
import { faker } from '@faker-js/faker';


faker.seed(42);
faker.setDefaultRefDate('2026-01-01T00:00:00.000Z');


const data = fakeFoo();
// always returns the same output
```

## Custom Faker Instance

[Section titled “Custom Faker Instance”](#custom-faker-instance)

You can pass your own [faker instance](https://fakerjs.dev/api/faker.html) via the `faker` option for runtime locale switching or other customizations.

```ts
import { faker } from '@faker-js/faker/locale/de';


const data = fakeFoo({ faker });
```

## API

You can view the complete list of options in the [UserConfig](https://github.com/hey-api/hey-api/blob/main/packages/openapi-ts/src/plugins/@faker-js/faker/types.ts) interface.

## Examples

You can view live examples on [StackBlitz](https://stackblitz.com/orgs/github/hey-api/collections/openapi-ts-examples) or on [GitHub](https://github.com/hey-api/hey-api/tree/main/examples).
