Interact with GraphQL using Express(Node JS)

Hi developers! I hope you are with me.. I started this GraphQL article series since I felt it's an amazing query language to practice. It's really cool! So I will continue this series with a set of articles based on the experience I'm getting after trying something with this . I must say, this is still new for me and let me introduce as a newbie to GraphQL. If you haven't read my previous introduction article on GraphQL, visit the below link to read it.

Today I will try to guide you to get a hands on experience with GraphQL using Express JS. I'm sure you will like it!

Node JS and NPM should be installed in your computer. That'a all!

Let me give a brief on this practical work. Here we are just trying to integrate GraphQL into an Express JS server(Node JS). Later I will bring you more on working with complex situations with Express.
Let's start the work!

1. Setup an Express Server

We are going make a folder called gq-express. Name it as you want. Then go into the folder using terminal or cmd. We have to initiate the process to create a Node JS project in this folder. So type npm init to start it. You will prompt several questions looking for answers. You can just enter them as you want. If you are not aware of this, read the first part of this article and it will help you in this case.

As my entry point is app.js, I create a new file called app.js in the project folder. This has the server  implementation. 
Since we use Express, we have to install NPM module to use it. Open a terminal and type 
npm install express

After installation is done, we can code to implement the server. Then app.js file will be like this..

const express = require('express');
const app = express();
const port = 4000;

app.listen(port, () => {
console.log('Server Started');
Now run the server by typing the command node app.js. The open web browser and type localhost:4000. You can see a console log on the terminal/cmd now. Server is up now!!! For further improvement I would like you to invite to install a npm package called nodemon. Because whenever we make changes in the Express code, we have to stop the server and restart it to track the latest changes. By installing nodemon, it will always running and tracking the chnages. It will automatically restart the server. Install using the below command.
npm install nodemon

2. Integrate GraphQL into the server

Now we have to install NPM packages to introduce GraphQL to the Express server. There are two packages to be installed. One is global package and the other one is express specified package. Let's install them using terminal.
npm install graphql express-graphql

Then we are going to require the express-graphql package with a variable. It will used as a middleware.

const graphQLHttp = require('express-graphql');
app.use('/graphql', graphQLHttp({


Add this code into the server. Here we register an end point to communicate with GraphQL. That endpoint will be and go to http://localhost:4000/graphql URL. You must get and error JSON output like this..

It says that GraphQL middleware needs a schema to deal with. Schema describes the object types and relations between object types. It is the file that includes the queries to enter to the graph used in GraphQL. So we need a schema and also a scenario to make a schema based on it. So I have talked about a library scenario in the introduction article. You should refer that one. Simply imagine that we are having a library with books. Books have authors. That's all. So the graph will look like this. We send requests to get books and authors.

3. Create a schema for the scenario

Now create a new folder called schema or any other name and create a file called schema.js. First grab the code in the following GIST and let me explain it next.

I will go from top to bottom.. Some comments are also there for your understanding.

First we need the global graphql package for the coding. We have to grab some items from this package. Those imported ones are GraphQLObjectType, GraphQLString, GraphQLSchema, GraphQLID. I have assigned them at the next line. GraphQLObjectType is for creating new objects and GraphQLSchema is for referring to a schema related to graphql. GraphQLString and GraphQLID are needed to define the types of attributes in objects. We can not use just String or ID here. We must import these from graphql.

Dummy data
For initial try, we need some data. Still we have not connected with a database or any other data source. That's why we need this books array. It contains 3 objects having title, category and id as its fields/attributes.

Declare first object type
In GraphQL environment, we need object types to deal with data. They are just piece of codes explaining the object structures. Since we create this for a library, I'll get the Book object type first. I have named it as BookType and created in as a GraphQLObjectType. It should have a name. Later this name will be used in relations. Then fields is a function that carrying the object attributes. There we define the types with already imported types such as  GraphQLString and GraphQLID.

Define Root Query
Root query in the entering query to the graph. So, I will declare one functionality as the root query. It's fetching book by ID. First we give a name to identify it uniquely. Then we define the fields. This time it's not a function! You can see the basic structure of book here. This book word is very important! It's the word we are going to use to deal with queries. You can see it later.
        book: {
            type: BookType,
            args: {id: {type: GraphQLString}}
There's a function called resolve(). This has the duty to return the needed data for a particular functionality. We use lodash to talk with data. It's a utility package available in NPM which can be used to make connections to communicate with data. No need of database models here. And we are not going to implement DB connections in this article.

return lodash.find(books, {id:});
This line will tell lodash to return the book with the ID passed in as a parameter. So we have to send request in a way like this.. I will show you how to send them.
            book(id: 1) {

Export module
This schema is exported to be available in the whole project with a root query. It's needed since the graph in GraphQL needs an entry point.

4. Modify GraphQL endpoint 

Now our schema is ready! Go to app.js again and modify the endpoint like this.

app.use('/graphql', graphQLHttp({

Now go to URL => http://localhost:4000/graphql in your browser. Did it throw an error? Look at the below error. This must be the error.

GraphQL provides an interactive UI through this pre-defined URL to deal with our back-end data. This URL needs a query string. We have to provide it. Because when we provide a query to GraphQL, it takes the query in the below format..
We have set a query variable for RootQuery when we export the schema module. Look at the last code lines in schema file. So we have to setup graphiql : true to enable this querying process.

So when we enable it, this error will not be there. So another simple modification is needed for graphql endpoint. Grab the below code and replace!

app.use('/graphql', graphQLHttp({
  graphiql: true

So final version of our Express server is included in the following gist. Get it!

Now again go to the URL => http://localhost:4000/graphql
What is the output? An interface like this?

So guys, this is the UI provided by GraphQL to communicate with data. It can send requests to our server and get responses. I'll present a simple demo on this.

5. Test the queries with GraphQL

For now, we are going to send a request to fetch a book from our data array. There's a defined way to send a request. The words will be suggested automatically what should be used, when you type on the left panel. I told that book word will be important. Here we must use it to fetch a book by ID.
Let's try one query! The below image includes the request to fetch the book with ID 1.

The response will be..

I have mentioned in my introduction, in GraphQL we can declare the data attributes we want. So, there's no waste. It leads to performance improvements since it does not go for all the attributes in each object. It just take the values we define. If you don't want id, you can remove it. Send the below request also.
            book(id: 1) {

Response should be like this... It returns the data belongs to the fields we define..

This is the end of the article guys! I have just started trying GraphQL with Express JS.. I will update more on this topic in future. Next article will be based on more object types and relations with GraphQL according to this library scenario,most probably.

Till then, good bye guys!

No comments :