JS - Mocking a GraphQL API with GraphQL Faker
Tags: graphql, javascript, webdev, beginners
Published: 2021-07-30 13:01:13

Mock API's are very useful when you need to "hit the ground running" with the front-end of a project. There are times when we need to have something visual to validate an idea with a client or to move forward with the interface while the back end is still being built.

Two weeks ago I published another article about it, explaining [how to mock a REST API using JSON Server](https://dev.to/vcpablo/js-mocking-a-rest-api-with-json-server-368).

TL;DR

This time I'm going to write about how to mock a [GraphQL](https://graphql.org/) API using [GraphQL Faker](https://github.com/APIs-guru/graphql-faker).

### GraphQL

Assuming you already know the basics of how GraphQL works, I'm not going to dive deep into its details. But, just to contextualize this article, according to [GraphQL official website](https://graphql.org/):

> GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data.

and

> Apps using GraphQL are fast and stable because they control the data they get, not the server.

### Mocking a GraphQL API

Building a fake GraphQL API is not difficult at all and all you need to do is:

- install [GraphQL Faker](https://github.com/APIs-guru/graphql-faker) package;
- configure a `.graphql` file containing the schema definitions (types, inputs, queries and mutations);
- take advantage of the [Faker JS](https://github.com/marak/Faker.js/) extension to easily mock contextualized data.

#### Installing GraphQL Faker

First, add GraphQL Faker package to your project.
If you need to build a VueJS project but you don't know where to start from, check [this article of mine](https://dev.to/vcpablo/vuejs-one-more-way-of-structuring-your-project-13mj) where I explain how I structure my new VueJS projects from scratch.
If your project is not going to be written in VueJS (sorry to hear that :(), you may check your favourite JavaScript framework's tutorial page to see how to start a fresh new project with it or even built it from scratch. These are the most common JavaScript ones:

- [React](https://reactjs.org/docs/create-a-new-react-app.html)
- [Angular](https://angular.io/guide/setup-local)
- [NodeJS](https://dev.to/brudhu/creating-my-first-node-js-app-30kk)

Access its root directory and, in a terminal window, execute the following command:

```
npm install graphql-faker --save-dev
```

_Notice that we'll use `--save-dev` flag to install this dependency only for development since the production version of the application will require the real GraphQL API to work_

#### Configuring the Schema - Types
This is the most important part of building your mocked GraphQL API. By configuring the schema, you will be able to really use the API to return data as you need.

_If you still don't know how a GraphQL Schema is configured, take a look at [this link](https://graphql.org/learn/schema/)._

Let's imagine a simple application that needs to display a list of users and details of their respective addresses like street, city and country.

In this case, we need to create these two _types_ within our `schema.graphql` file. The good thing about GraphQL Faker is that it already provides the `@fake` and `@examples` directives that allow us to define possible values to be mocked when retrieving data from our mocked API. Check this out:

```graphql
type User {
  name: String @fake(type: firstName)
  age: Int @examples(values: [20 25 30 35])
  address: Address
}

type Address {
  street: String @fake(type: streetName)
  number: Int @examples(values: [303 409])
  city: String @fake(type: city)
  state: String @fake(type: stateAbbr)
  country: String @fake(type: country)
}
```
Obs.: Faker JS provides several different types of fake data that will allow you to create real-world mocked data according to your needs. I'm not sure exactly [which types](https://github.com/marak/Faker.js/#api-methods) are available to be used along with GraphQL Faker, but most of them are according to some tests I've made.

#### Configuring the Schema - Queries/Mutations

After configuring the `Types`, we need to set the `Queries` and `Mutations` to be able to perform operations.

_Keep in mind that the `Mutations` will not create any data anywhere like [JSON Server mock API](https://dev.to/vcpablo/js-mocking-a-rest-api-with-json-server-368) but they will support you in building the correct inputs the front end will need to send when calling them._

When creating a `Query` we may define which is the type it should return and also the minimum and maximum size of the array it will return. In the example below, the `User` query, the API will return lists containing between 3 and 20 users, randomly each time we call it.

```graphql
type Query {
  Users: [User] @listLength(min:3, max: 20)
}
```

You may also define an `input` types and `Mutations` to allow your front end to perform these operations without receiving a `400` or `404` error.

Imagine that your application will allow people to create users and their address. So, we need to define, in our Schema a `UserInput` and an `AddressInput` (you may call it whatever you prefer) to be used in the mocked Mutation we'll create later:

```graphql
input UserInput {
  name: String
  age: Int,
  address: AddressInput
}

input AddressInput {
  street: String
  number: Int
  city: String
  state: String
  country: String
}
```

After creating the inputs properly, we can define our mutation:

```graphql
type Mutation {
  CreateUser(user: UserInput): User
}
```

#### Running GraphQL Faker

In order to test the mocked API you've just created, first we need to include a new `script` into our `package.json` file like the following:

```json
"mock:api": "graphql-faker ./schema.graphql"
```

Then, all you need to do is run the command on a terminal using:

```
npm run mock:api
```

By running it you will see the following information:

![Running GraphQL Faker mock API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9n8pw8d7evoybzf6xzh2.png)

The three links are:

##### Interactive Editor
A text editor where you can update your schema
![GraphQL Schema Interactive Editor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qkpfdcr4nkqusj8mc2d3.png)
 
##### GraphQL API
A playground where you can test all of your queries and mutations and also check all of the types defined in the schema.
![GraphQL Playground](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zpr9i3vtgm00yufqrn5f.png)
 
##### Voyager
An interactive graph representation of your schema
![GraphQL Voyager](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l9w4a0pgo0jlxxs9n820.png)

_The ports may defer. If you want to define a specific port to use the GraphQL Faker, you may define it in the script in the `package.json` file._

```json
// It will run on port 4000

"mock:api": "graphql-faker --port 4000 ./schema.graphql"
```


#### Testing GraphQL Faker API

Access the **GraphQL API** address (http://localhost:PORT/graphql) and try out your query and check the full (and interactive) documentation of your schema :).

<a href="https://www.loom.com/share/e2239a80be6e4d7b99d3c4e75de89884">
    <div>GraphiQL Playground - Watch Video</div>
    <img style="max-width:300px;" src="https://cdn.loom.com/sessions/thumbnails/e2239a80be6e4d7b99d3c4e75de89884-with-play.gif">
  </a>

---

You can find a simple and fully functional project similar to what we've built together in this article at [this repo](https://github.com/vcpablo/graphql-mock-api).

### Considerations

If you got until this point, it means you've read the last piece of text from a series of 16 articles, published weekly since April 6th, when I decided to write about [Different ways of implementing v-model (in VueJS)](https://dev.to/vcpablo/vuejs-2-different-ways-to-implement-v-model-1mjf).

The inspiration came after reading an article that said that "every developer should write". Unfortunately, this article is no longer available on the internet but its message was transmitted.

I'm not sure if I'll keep writing and, if I decide so, I don't know how frequently, but the most important thing is that I achieved my personal goal: 1 published article per week along 16 weeks in a row.

During this period three of my articles were delivered in [one of the biggest VueJS newsletters](https://vuejsdevelopers.com/newsletter/) around the world and one person reached out to me with an international job offer.

You can see more about these stories in my [LinkedIn](https://linkedin.com/in/pablo-veiga).

Follow me here, if you still do not and I'll bring you news soon!
Thanks for all of the support!

Comment and share!