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.
TL;DR
This time I'm going to write about how to mock a GraphQL API using 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:
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 package;
- configure a
.graphql
file containing the schema definitions (types, inputs, queries and mutations); - take advantage of the 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 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:
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.
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:
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 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 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.
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:
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:
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:
"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:
The three links are:
Interactive Editor
A text editor where you can update your schema
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.
Voyager
An interactive graph representation of your schema
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.
// 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 :).
GraphiQL Playground - Watch Video
You can find a simple and fully functional project similar to what we've built together in this article at this repo.
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).
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 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.
Follow me here, if you still do not and I'll bring you news soon!
Thanks for all of the support!
Comment and share!
Top comments (0)