---
title: "How to Mock a GraphQL API"
canonical: https://cesarfelipe.dev/articles/how-to-mock-a-graphql-api/
published: 2021-10-30
updated: 2026-12-05
author: César Felipe
---

**TL;DR**

- You can mock an entire GraphQL API from the real one in two steps.
- Generate the schema through introspection with GraphQL Codegen, then serve it with GraphQL Faker, which returns fake but realistic data.
- Directives like @fake, @examples and @listLength shape that data, so the frontend keeps moving when the backend is down or unfinished.

At this point, you’ve likely worked with a [GraphQL](https://graphql.org/) API. But did you know that, during development, it’s a lot easier to just mock the entire API?

## Why create a mock API?

Before I show you how to mock your API, here are the benefits of creating a mock:

1.  The frontend team doesn’t get blocked if/when the server goes down;
2.  The frontend team can start to develop together with the backend team, instead of waiting for an API to be finished;
3.  It’s easier to test the UI;
4.  Integration tests are easier and faster to write;
5.  You won’t waste resources hitting the real API.

Those are just some of the benefits of mocking your API instead of only using the real one. At cVortex, I built a mocked GraphQL BFF so frontend teams kept working when backend environments were down; this guide shows the idea in its simplest form.

## Which tools do you need to mock a GraphQL API?

We will use two main tools.

The first is [GraphQL Codegen](https://the-guild.dev/graphql/codegen). It runs introspection and gives you the schema of the real API.

The second is [GraphQL Faker](https://github.com/graphql-kit/graphql-faker). It creates a fake server that simulates the real API.

## Step 1: set up the project

First, create a new folder and start a Node.js project:

```bash
mkdir mock-api && cd mock-api && yarn init -y
```

Then install the dependencies:

```bash
yarn add -D @graphql-codegen/cli @graphql-codegen/schema-ast graphql graphql-faker
```

That’s all you need. The original version of this list also had `@graphql-codegen/introspection`, `@graphql-codegen/urql-introspection` and `graphql-codegen`. The first two generate introspection JSON, which we don’t use here, and `graphql-codegen` is an abandoned 2016 package from the Apollo codegen era, not The Guild’s Codegen CLI. Current Codegen versions also need a recent Node.js, so check the `engines` field if the install complains.

## Step 2: generate the schema from the real API

Now we can start coding. First, generate a schema from your real API by running the introspection query with [GraphQL Codegen’s programmatic API](https://the-guild.dev/graphql/codegen/docs/advanced/programmatic-usage):

*generate-schema.mjs*

```js
import { generate } from "@graphql-codegen/cli";

const generateSchema = async () => {
  await generate(
    {
      schema: [
        {
          "https://your-server-url.com/graphql": {
            headers: { Authorization: "Bearer XXXXX" }, // Only if your API needs it
          },
        },
      ],
      generates: {
        "schema.graphql": {
          plugins: ["schema-ast"],
          config: {
            includeDirectives: true,
          },
        },
      },
    },
    true // Write the output to disk
  );
};

generateSchema().catch((error) => {
  console.error(error);
  process.exit(1);
});
```

Run it with `node generate-schema.mjs`. It creates a file called **schema.graphql** at the root of your project. This is what the mock server will use to simulate the real API.

Two fixes from the first version of this snippet: headers go inside the schema entry for that URL, not at the root of the config, and the function has to actually be called. I also dropped `federation: true`. Only turn it on if your API is an Apollo Federation subgraph; otherwise it adds federation directives the mock server doesn’t know about.

Don’t commit a real token in this file. Read it from an environment variable.

## Step 3: run the mock server

Now we just need to run the server with the schema.graphql file. The simplest way is two scripts in `package.json`:

*package.json*

```json
{
  "scripts": {
    "schema": "node generate-schema.mjs",
    "mock": "graphql-faker schema.graphql"
  }
}
```

Then `yarn schema && yarn mock`. Package scripts can see binaries in `node_modules/.bin`, so the locally installed `graphql-faker` just works.

If you’d rather start it from Node, use `spawn`, not `exec`:

*run-mocked-server.mjs*

```js
import { spawn } from "node:child_process";

const runMockedServer = () => {
  const server = spawn("npx", ["graphql-faker", "schema.graphql"], { stdio: "inherit" });

  server.on("error", (error) => console.error(error));
};

runMockedServer();
```

The old version called `exec("graphql-faker schema.graphql")`, which had two problems: a plain shell doesn’t find a locally installed binary, and `exec` buffers the output of a process that never ends, so you never see the server logs. It also defined `runMockerServer` and called `runMockedServer`, which is a `ReferenceError` before anything runs.

The mock server is now available at http://localhost:9002, and the GraphQL endpoint your frontend should point to is http://localhost:9002/graphql. This is where the magic happens.

## Step 4: shape the fake data with directives

At http://localhost:9002/editor, you can edit the whole schema that was generated through introspection.

```graphql
type Company {
  id: ID
  name: String @fake(type: companyName)
  industry: String
    @examples(values: ["IT", "Manufacturing", "Medicine", "Media"])
  employees: [Employee!] @listLength(min: 5, max: 10)
}

type Employee {
  id: ID
  firstName: String @fake(type: firstName, locale: en_CA)
  lastName: String @fake(type: lastName, locale: en_CA)
  address: String @fake(type: streetAddress, options: { useFullAddress: true })
  subordinates: [Employee!] @listLength(min: 0, max: 3)
  company: Company
}

type Query {
  employee(id: ID): Employee
  company(id: ID): Company
  allCompanies: [Company!]
}
```

*Graphql Editor*

There are three main directives you can use:

1.  `@fake`: specifies the kind of value you want, e.g. companyName, fullName, firstName, lastName.
2.  `@examples`: when you need specific values, e.g. Male or Female, pass an array of allowed values as the argument.
3.  `@listLength`: specifies the size of an array with min and max values.

If we run a query against the schema above, we receive the following data:

```graphql
{
  company {
    id
    name
    industry
    employees {
      id
      firstName
      lastName
      address
    }
  }
}
```

```json
{
  "data": {
    "company": {
      "id": "NjY1Njg5Mzc2OA==",
      "name": "Daniel - Hauck",
      "industry": "Media",
      "employees": [
        {
          "id": "NDg2MDM3ODQ4OQ==",
          "firstName": "Esteban",
          "lastName": "Hermann",
          "address": "4016 Wilkinson Curve Suite 868"
        },
        {
          "id": "NjA2MTcxNjQ1OQ==",
          "firstName": "Beryl",
          "lastName": "Balistreri",
          "address": "165 Immanuel Village Apt. 144"
        },
        {
          "id": "MTc1MTU1NTMyMw==",
          "firstName": "Deshaun",
          "lastName": "Kutch",
          "address": "5556 Gorczany Port Suite 010"
        },
        {
          "id": "NDQwOTc1MTMyOA==",
          "firstName": "Mariam",
          "lastName": "Mraz",
          "address": "9271 Donnelly Run Apt. 140"
        },
        {
          "id": "OTI2NTY5MzMwMA==",
          "firstName": "Mertie",
          "lastName": "Volkman",
          "address": "58877 Kilback Plaza Suite 309"
        }
      ]
    }
  }
}
```

Now we can change the schema in the editor.

I changed `Company.name` from companyName to lorem words, limited the size of the employees array, and restricted the examples for `Company.industry`:

```graphql
type Company {
  id: ID
  name: String @fake(type: lorem, options: { loremSize: words })
  industry: String
    @examples(values: ["IT", "Manufacturing"])
  employees: [Employee!] @listLength(min: 1, max: 2)
}

type Employee {
  id: ID
  firstName: String @fake(type: firstName, locale: en_CA)
  lastName: String @fake(type: lastName, locale: en_CA)
  address: String @fake(type: streetAddress)
  subordinates: [Employee!] @listLength(min: 0, max: 3)
  company: Company
}

type Query {
  employee(id: ID): Employee
  company(id: ID): Company
  allCompanies: [Company!]
}
```

Running the query again, we receive the following result:

```graphql
{
  company {
    id
    name
    industry
    employees {
      id
      firstName
      lastName
      address
    }
  }
}
```

```json
{
  "data": {
    "company": {
      "id": "MzQxMzU5MDE4Mw==",
      "name": "provident maiores qui",
      "industry": "Manufacturing",
      "employees": [
        {
          "id": "MjI0ODA2ODg4OQ==",
          "firstName": "Kayli",
          "lastName": "Corkery",
          "address": "41722 Hilpert Common"
        }
      ]
    }
  }
}
```

## Keeping the mock in sync with the real API

There’s one catch that bites everyone eventually. When you save in the editor, GraphQL Faker writes your changes back to `schema.graphql`. That’s great, until the real API changes and you run the introspection again: Codegen overwrites the file, and every `@fake` and `@examples` you added is gone.

Two ways around it:

1.  Keep the generated schema and your directives in version control, and review the diff after each regeneration. It works, but it’s manual.
2.  Don’t mock the whole API. GraphQL Faker has an extend mode: it proxies the real server and only fakes what you add in a separate file.

*schema.extension.graphql*

```graphql
extend type Company {
  foundedYear: Int @examples(values: [1998, 2005, 2017])
}
```

```bash
graphql-faker schema.extension.graphql --extend https://your-server-url.com/graphql --header "Authorization: Bearer XXXXX"
```

Extend mode is what I’d reach for when the backend is up but a new field isn’t shipped yet. You get real data plus the one field you’re waiting for. When the whole backend is down, which is the case that started this post, you still need the full schema from step 2.

One more thing worth knowing: the last GraphQL Faker release on npm is from 2023, and the project doesn’t move much. It still does the job described here, but don’t expect new features.

And that’s it: that’s everything you need to mock your GraphQL API. I hope you found this short guide useful.

## Key takeaways

-   A mock API keeps the frontend unblocked when the server is down, and lets frontend and backend work in parallel instead of in sequence.
-   GraphQL Codegen introspects the real API and writes its schema to `schema.graphql`.
-   GraphQL Faker serves that schema with fake data at `localhost:9002/graphql`, with an editor at `/editor`.
-   `@fake`, `@examples` and `@listLength` control what the fake data looks like, so it stays close to production.
-   The editor saves into `schema.graphql`, so regenerating the schema wipes your directives. Version the file, or use `--extend` to fake only the fields that don’t exist yet.
