GraphQL Tutorial #2 – Setting up a Basic Project in GraphQL

Introduction:

GraphQL is a query language used for APIs. Unlike REST, GraphQL has only one endpoint and client can ask for what is actually required. We can write a GraphQL server in many popular programming languages like JavaScript, Java, R, Python etc. and it is not tied to any specific database architecture.

In this tutorial, we will learn how to create one basic GraphQL server with Node.js using express framework. Our program will show you how to perform CRUD (create, read, update, delete) operations using GraphQL. We will also learn how to test GraphQL queries using a in-browser interface called GraphiQL.

Initial setup :

Create one empty project by using ‘npm init’ command. We are going to use the following ‘npm’ modules in this project :

express :

This npm module is required for installing the express framework in our project.

graphql :

npm module for GraphQL.js

express-graphql :

npm module for using graphql with express as a middleware.

nodemon :

‘nodemon’ is used to restart a node server automatically. It continuously monitors the changes in the source files and automatically restarts it if you make any change. It is a useful tool for development.

uniqid :

This module is required to create a unique id. It generates unique id string based on the process, machine name and current time.

Install these modules using the below command :

npm i express graphql express-graphql nodemon uniqid

It will install all these modules in a folder called ‘node_modules’.

your final package.json file will look like below :

We have added one new ‘dev’ key inside the ‘scripts’ block. This is used to run the ‘nodemon server.js‘ command. ‘npm run dev’ will execute this command.

Starting a GraphQL server using express :

Let’s create one simple GraphQL server using the above modules. Using, ‘express-graphql’ module, we can create one express server with GraphQL server easily. Edit the ‘server.js’ file as like below :

In this program :

– We are using ‘express’, ‘express-graphql’ and ‘graphql’ libraries.

– ‘buildSchema’ is defined in ‘graphql’ and it is used to create one schema using GraphQL schema language. In this example,we have one query ‘message’ that takes one string as its parameter. We are using one ‘!’ to indicate that this parameter is required. Without this parameter, you can’t execute this query. The return value of the query is a string.

– ‘root’ is used to provide a resolver function for each endpoint. For ‘message’, it will return one string ‘Hello ${args.name}!’. ‘args.name’ is the ‘name’ we are passing in the query.

– Finally, we are starting the ‘express’ server on port ‘4000’.

If you have already started the server using ‘npm run dev’, ‘nodemon’ will detect the changes and restart the server on port ‘4000’.

Open ‘localhost:4000/graphql’ on your browser. You will see an interface like below :

This is ‘GraphiQL’,an in-browser GraphQL IDE that can be used for testing GraphQL queries.The ‘graphiql’ parameter in the above program needs to be set as ‘true’ for enabling this IDE. ‘graphiql’ comes with ‘express-graphql’ but we can also install it separately on other projects using ‘npm’ or ‘yarn’.

On the left side of the panel, enter the following query :

Click on the ‘play’ button and it will print the below output on the right panel :

Try changing the name and it will return different output for each input query.

More queries and mutation :

I hope that you got the basic understanding of GraphQL. Let’s build one user management application with the following functionalities :

– Get the list of all users

– Add a user

– Get a single user

– Delete a user

– Edit user

We are not going to use any database to store this info. We will use one local array to store them. If you restart your server, the data will be deleted.

User object :

Our array will hold user objects and we will perform all operations on these objects. A user object will hold the following parameters :

id : String type

name : String type

gender : String type

age : Int type

Open the ‘server.js’ file and change the buildSchema function as like below :

The final ‘server.js’ file will look like as below :

The server will run with this code without any queries.

a) Get the list of all users (Query):

We will use one array to hold the list of all users and using one query we will return this array.

Open the ‘server.js’ file and add one variable ‘userList’ to hold the list of all users :

‘users’ query will return one array of ‘User’ objects. Optionally, we can also get the users based on the ‘gender’ value. ‘gender’ is optional.

Now, create one function to return all current users :

Here, ‘args’ is the argument graphql will provide us. We are checking if the ‘gender’ property is available in ‘args’. If it is, we are filtering out the ‘userList’ based on ‘gender’. Else, we are returning the complete list.

Change the ‘root’ as like below :

That’s it. Run the below query in the GraphiQL :

As you can see that we are getting one empty list of ‘users’ from our server as we don’t have any users available currently.

b) Add a user (Mutation):

For writing data, we can write a query. But as per the documentation, we should use a ‘mutation’ for any kind of data write. Similar to queries, mutation also returns a value.

Just like the above query operation, for adding a user, we need to add one mutation type in ‘buildSchema’ , one function for handling the operation and changes in the root variable.

Add one ‘mutation’ type inside ‘buildSchema’ :

We will pass the ‘name’, ‘gender’ and ‘age’ of the user and it will return one ‘User’ object, i.e. it will return the same object that is added.

Add one function to add one use object to ‘userList’ array :

This function will create and push one ‘User’ object to the ‘userList’. We are using ‘uniqid’ module to create one unique id for each user object. For using this module, you need to use the below import line :

Finally, add the below pairs inside the root variable :

add: addUser

Now, you can add one user using a ‘mutation’ query like below :

Execute this query and the output will look like below :

As you can see, the ‘id’ is assigned automatically to the newly created user. We are printing the ‘id’, ‘name’, ‘age’ and ‘gender’ of the new user. But you can also print only the values that are required.

Add a few more users using this mutation and get them using the ‘users’ query like below :

I have added three users here. We can also use the ‘users’ query to filter out the users based on the gender :

c) Get a single user, delete a user, edit a user :

Similar to the above two examples, we can write query and mutation to complete our application. Getting a single user is of ‘query’ type and ‘delete’/’edit’ user is of ‘mutation’ type.

The final server.js file looks like as below :

Here,

– ‘user’ query is to get a specific user. It takes the ‘id’ of a user and returns that ‘User’ object.

– ‘delete’ mutation is to delete a specific user. Using the ‘id’, we can delete one user. It returns the new user array.

– ‘edit’ mutation is for editing a user. We can edit the ‘name’ of a user using the ‘id’.

– ‘getUser’ function is to get a specific user

– ’deleteUser’ function is to delete a user

– ‘editUser’ is for editing a user

– the ‘root’ variable is also changed as per the above new addition.

 

Example :

Let’s try the above query and mutations with an example. I have added three users using the ‘addUser’ mutation.

  1. Get the list of all users :
  2. Get user with id “g2pc127bjv6mt1l2” :
  3. Edit user name with id “g2pc127bjv6mt1l2”
  4. Delete user with id “g2pc127bjv6mt1l2”

Conclusion :
Starting a GraphQL server is easier than any REST server. ‘express-graphql’ comes with the ‘GraphiQL’ browser IDE that makes the query and mutation more easier to debug. Using libraries like ‘Apollo’, we can easily integrate GraphQL with any other client projects like React, Angular, Android or iOS.

Tutorial Index:

  1. GraphQL Tutorial #1 -Introduction
  2. GgraphQL Tutorial #2 – Setting Basic Project in GraphQL
  3. GraphQL Tutorial #3 – GraphQL Components
  4. GraphQL Tutorial #4 – GraphQL Operations
  5. GraphQL Tutorial #5 – Introduction to Apollo GraphQL
  6. GraphQL Tutorial #6 – 51 Most Important GraphQL Interview Q&A

Add a Comment

Your email address will not be published. Required fields are marked *