The communication and data transfer between the front end and backend of any application occurs through APIs (Application Programming Interface). There are many different types of APIs used to communicate between the front and back-end applications like RESTful API, SOAP API, GraphQL API, etc. The GraphQL API is a relatively new technology, and it is much faster than other types of APIs available. Fetching data from the database using GraphQL api is much faster than the REST API. While using GraphQL API, the client has control to fetch only the required data instead of getting all the details; that is why GraphQL API works faster than REST API.

Installing Packages

We will build a node.js application using GraphQL API, so we need to install node.js and npm for this before starting the project.

ubuntu@ubuntu:~$ sudo apt-get update -y

ubuntu@ubuntu:~$ sudo apt-get install nodejs

ubuntu@ubuntu:~$ sudo apt-get install npm

Setting up Project

We will use the ‘express’ framework from node.js to build our application. Create a directory named ‘graphql’ and initiate the project.

ubuntu@ubuntu:~$ mkdir graphql

ubuntu@ubuntu:~$ cd graphql/

ubuntu@ubuntu:~$ npm init -y

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/01/echo/image4-24.png" data-lazy- height="426" src="data:image/svg xml,” width=”722″>

MongoDB Setup

In our GraphQL project, we will use MongoDB as our database. MongoDB is a schemaless database and stores data in the form of key pairs. In order to install mongoDB, follow the given steps.

Import the public GPG key for MongoDB.

ubuntu@ubuntu:~$ wget -qO – https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/01/echo/image6-19.png" data-lazy- height="126" src="data:image/svg xml,” width=”722″>

Create the list file for mongodb.

ubuntu@ubuntu:~$ echo “deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse” | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/01/echo/image5-21.png" data-lazy- height="146" src="data:image/svg xml,” width=”722″>

Update local repositories.

ubuntu@ubuntu:~$ sudo apt-get update -y

Install mongodb package.

ubuntu@ubuntu:~$ sudo apt-get install -y mongodb-org

Start and enable mongod.service.

ubuntu@ubuntu:~$ sudo systemctl start mongod.service

ubuntu@ubuntu:~$ sudo systemctl enable mongod.service

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/01/echo/image8-16.png" data-lazy- height="326" src="data:image/svg xml,” width=”722″>

Installing npm Modules

For our GraphQL application, we need to install some npm packages. We will install cors, express, body-parser, mongoose, etc.

ubuntu@ubuntu:~$ cd graphql/

ubuntu@ubuntu:~$ npm install cors express body-parser mongoose –save

To create a GraphQL api, we need to install an extra npm package named ‘apollo-server-express.’ This npm package is used to run graphQL server with all Node.js HTTP frameworks like ‘express.’

ubuntu@ubuntu:~$ npm install apollo-server-express –save

Defining MongoDB Schema

Now we have our environment set up for our GraphQL application in Node.js, and it is time to define a schema for our application. Create a file ‘models/student.js’ in the project root directory.

// defining student schema

const mongoose = require(‘mongoose’);

const studentSchema = new mongoose.Schema({

     name: {

          type: String,

          required: true

     },

     class: {

          type: Number,

          required: true

     },

     major: {

          type: String,

          required: true

     }

}, {

     timestamps: true

});

const Student = mongoose.model(‘Student’, studentSchema);

module.exports = { Student, studentSchema }

In the above-defined schema, every student must have a name, class, and major.

Building GraphQL API

After creating the Student schema, we will now build GraphQL API. Create a ‘schema.js’ to write GraphQL parameters. There are two parameters, ‘types’ and ‘resolvers,’ used in GraphQL API. In ‘types,’ we will specify our schema, the queries (e.g., Making GET requests), and mutations (e.g., Making UPDATE or DELETE requests) to the specified schema. We will write the different methods defined in ‘types’ to link the queries and mutations with the database in ‘resolvers.’

// importing schema and module

const { gql } = require(‘apolloserverexpress’);

const Student = require(‘./models/student’).Student;

// Defining Schema, Query, and Mutation Type

const typeDefs = gql `

   type Student {

      id: ID!,

      name: String!,

      class: Int!,

      major: String!

   }

   type Query {

      getStudents: [Student],

      getStudentById(id: ID!): Student

   }

   type Mutation {

      addStudent( name: String!, class: Int!, major: String! ): Student

      updateStudent( name: String!, class: Int!, major: String! ): Student

      deleteStudent( id: ID! ): Student

   }`

// Defining Resolvers

const resolvers = {

   Query: {

      getStudents: (parent, args) => {

         return Student.find({});

      },

      getStudentById: (parent, args) => {

         return Student.findById(args.id);

      }

   },

   Mutation: {

      addStudent: (parent, args) => {

         let student = new Student({

            name: args.name,

            class: args.class,

            major: args.major

         });

         return student.save();

      },

      updateStudent: (parent, args) => {

         if(!args.id) return;

         return Student.findOneAndUpdate({

            _id: args.id

         },

         {

            $set: {

               name: args.name,

               class: args.class,

               major: args.major

            }

         },

         { new: true }, (err, Student) => {

            if(err) {

               console.log(err);

            } else {};

         })

      }

   }

}

module.exports = {

   typeDefs,

   resolvers

}

Creating GraphQL API Server

Now we are almost done creating the GraphQL Application. The only step left is to create the server. Create a file named ‘app.js’ to configure server parameters.

// importing required packages

const express = require(‘express’);

const mongoose = require(‘mongoose’);

const bodyParser = require(‘bodyparser’);

const cors = require(‘cors’);

const { ApolloServer } = require(‘apolloserverexpress’);

// importing schema

const { typeDefs, resolvers }= require(‘./schema’);

// connecting to MongoDB

const url = “mongodb://127.0.0.1:27017/students”;

const connect = mongoose.connect(url, { useNewUrlParser: true });

connect.then((db) => {

   console.log(‘Connection Successful’);

}, (err) => {

   console.log(err);

});

// creating server

const server = new ApolloServer({

   typeDefs: typeDefs,

   resolvers: resolvers

});

const app = express();

app.use(bodyParser.json());

app.use(*, cors());

server.applyMiddleware({ app });

app.listen( 8000, () =>

{

   console.log(‘listening to 8000’);

})

Testing the GraphQL API

We have our graphQL server up and running on port 8000, and it is time to test the GraphQL API. Open the GraphQL webpage in the browser by visiting the following url.

http://localhost:8000/graphql

And it will open the following webpage.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/01/echo/image7-15.png" data-lazy- height="382" src="data:image/svg xml,” width=”798″>

Add the student to the database using graphQL API.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/01/echo/image2-31.png" data-lazy- height="349" src="data:image/svg xml,” width=”1220″>

Similarly, add more students, and after adding the student, get all the students using GraphQL API.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/01/echo/image1-33.png" data-lazy- height="468" src="data:image/svg xml,” width=”1352″>

Note the ID of any of the Students and get the specific student using its id.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/01/echo/image3-29.png" data-lazy- height="395" src="data:image/svg xml,” width=”1220″>

Conclusion

Fetching data from the database using the standard REST API makes the query slow as sometimes we get more data than required. Using GraphQL, we can fetch exactly the required data that makes the GraphQL API faster. In this demo project, we only have a single schema, so we have created GraphQL API for that single schema. Also, we have defined three to four methods for the schema. You can create more than one query or mutations according to your application.

About the author

<img alt="Usama Azad" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/01/echo/usama-1-150×150.jpg60120ac7f203c.jpg" height="112" src="data:image/svg xml,” width=”112″>

Usama Azad

A security enthusiast who loves Terminal and Open Source. My area of expertise is Python, Linux (Debian), Bash, Penetration testing, and Firewalls. I’m born and raised in Wazirabad, Pakistan and currently doing Undergraduation from National University of Science and Technology (NUST). On Twitter i go by @UsamaAzad14