César Felipe

7 min readUpdated

How to Mock a GraphQL API

Mock a GraphQL API from its real schema: introspect with GraphQL Codegen, serve fake data with GraphQL Faker, shape it with @fake, @examples, @listLength.

  • Frontend
  • GraphQL
On this page

At this point, you’ve likely worked with a GraphQL 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. It runs introspection and gives you the schema of the real API.

The second is 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:

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

Then install the dependencies:

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

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:

generate-schema.mjs

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

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

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

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

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();
js

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.

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

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:

{
  company {
    id
    name
    industry
    employees {
      id
      firstName
      lastName
      address
    }
  }
}
graphql
{
  "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"
        }
      ]
    }
  }
}
json

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:

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!]
}
graphql

Running the query again, we receive the following result:

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

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

extend type Company {
  foundedYear: Int @examples(values: [1998, 2005, 2017])
}
graphql
graphql-faker schema.extension.graphql --extend https://your-server-url.com/graphql --header "Authorization: Bearer XXXXX"
bash

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.