AppDividend
Latest Code Tutorials

GraphQL Tutorial For Beginners

305

Get real time updates directly on you device, subscribe now.

GraphQL Tutorial is the topic, we will discuss today. GraphQL is a query language for APIs and runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools. GraphQL can be used with any backend framework or programming language.

GraphQL Tutorial For Beginners

We will start this tutorial by first installing the GraphQL itself. So first create a project directory and go into that directory. As a package manager, I am using Yarn, so if you have not installed, then you can pull it through npm. If you have not installed Node.js then please first install and then you can able to pull any npm packages.

mkdir graphqltutorial
cd graphqltutorial

Okay, now install GraphQL using the following command.

yarn add graphql

Open that folder inside Visual Studio Code editor using the following command.

code .

If you are using different editor then simply open our project folder inside that editor.

Next step is to create a Node.js web server. So create a server.js file inside the root of the project.

// server.js

const { graphql, buildSchema } = require('graphql');

// Construct a schema, using GraphQL schema language
const schema = buildSchema(`
  type Query {
    hello: String
  }
`);

// The root provides a resolver function for each API endpoint
const root = {
  hello: () => 'Hello! Welcome To GraphQL'
};

// Run the GraphQL query '{ hello }' and print out the response
graphql(schema, '{ hello }', root).then((response) => {
  console.log(response);
});

Okay, now save the file and go to the terminal and run the node server.

node server

You will see the response in the log.

Node js command line

 

A GraphQL service is created by defining types and fields on those types, then providing functions for each field on each type. In above example, we have defined the String hello. Next, we have created the resolver function that returns its value which is “Hello! Welcome to GraphQL“.

Setup GraphQL Server with Express

Okay, so now install the following packages using Yarn.

yarn add express express-graphql nodemon

Okay, now import the express module inside the server.js file.

// server.js

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

app.listen(4000, () => {
  console.log('Server is running');
});

Next step is to create a schema. So inside the root folder, create one file called schema.js.

After that, first, we will import some data types from GraphQL module. So let us do that inside schema.js file.

// schema.js

const {
    GraphQLObjectType,
    GraphQLString,
    GraphQLSchema,
    GraphQLInt
} = require('graphql');

Let us create a sample data inside the schema.js file because we need the sample data to query. So that we can get the result.

// schema.js

const employees = [
    {
        id: 1,
        name: 'Krunal',
        email: 'krunal@appdividend.com'
    },
    {
        id: 2,
        name: 'Ankit',
        email: 'ankit@appdividend.com'
    },
    {
        id: 3,
        name: 'Rushabh',
        email: 'rushabh@appdividend.com'
    }];

Now, we need to define the EmployeeType. We need to query the array of employees. So first we define the schema for the EmployeeType.

// schema.js

const EmployeeType = new GraphQLObjectType({
    name: 'Employee',
    fields: () => ({
        id: {type: GraphQLInt},
        name: {type: GraphQLString},
        email: {type: GraphQLString}
    })
});

Almost all of the GraphQL types you define will be object types. Object types have a name, but most importantly describe their fields. So we need to specify the fields for the EmployeeType. So we have defined three fields for our purpose, and that is id, name, and email. So, it simply means that we can query the data on these three fields. Either we can get all the three fields data, or we can apply some condition to get the required data. It is the structure of our query data. So we need to define it in an EmployeeType object.

Define RootQuery

Let us define the RootQuery.

// schema.js

const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
        employee: {
            type: EmployeeType,
            args: {
                id: {type: GraphQLInt}
            },
            resolve(parentValue, args) {
                for(let i=0; i<employees.length; i++) {
                    if(employees[i].id == args.id) {
                        return employees[i];
                    }
                }
            }
        }
    }
});

It also contains same name and fields. Here, fields are Type EmployeeType, which we have defined earlier. We will query the data based on the passed ID from the user. So employee function gets one argument and that is id. Later in the resolve, we have put the condition that if the passed ID is matched with the already defined array then we simply return that employee. So now, we have defined the schema and also write the logic that returns the exact data we have asked for. Now, the full code of this file schema.js file is as below.

// schema.js

const {
    GraphQLObjectType,
    GraphQLString,
    GraphQLSchema,
    GraphQLInt
} = require('graphql');

const employees = [
    {
        id: 1,
        name: 'Krunal',
        email: 'krunal@appdividend.com'
    },
    {
        id: 2,
        name: 'Ankit',
        email: 'ankit@appdividend.com'
    },
    {
        id: 3,
        name: 'Rushabh',
        email: 'rushabh@appdividend.com'
    }];

const EmployeeType = new GraphQLObjectType({
    name: 'Employee',
    fields: () => ({
        id: {type: GraphQLInt},
        name: {type: GraphQLString},
        email: {type: GraphQLString}
    })
});

const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
        employee: {
            type: EmployeeType,
            args: {
                id: {type: GraphQLInt}
            },
            resolve(parentValue, args) {
                for(let i=0; i<employees.length; i++) {
                    if(employees[i].id == args.id) {
                        return employees[i];
                    }
                }
            }
        }
    }
});

module.exports = new GraphQLSchema({
    query: RootQuery
});

Import schema.js inside a server.js.

So, our final server.js file looks like this.

// server.js

const express = require('express');
const app = express();
const expressGraphQL = require('express-graphql');

const schema = require('./schema');

app.use('/graphql', expressGraphQL({
  schema: schema,
  graphiql: true
}));

app.listen(4000, () => {
  console.log('GraphQL Server is running');
});

Now, if start the node.js server by the following command.

nodemon server

If you are getting an error, then please install nodemon globally on your machine using the following command.

yarn global add nodemon

It will resolve the issue and again hit the command. It will show us like that GraphQL Server is running on the console. Switch to the browser and hit the following URL.

http://localhost:4000/graphql

 

GraphQL Example

Of course, you see some comments on the screen but, at the starting of this interface, you will find the comments, I have removed because we do not need that. Instead, delete all the comments, and there, we need to write the query that describes how much data, we need.

Write the following query on the left-hand side panel.

{
  employee(id: 1) {
    name
    email
  }
}

It means that we only get the name and email of the employee, which has id = 1. Now, press the play button or cmd + return to see the fetching data.

{
  "data": {
    "employee": {
      "name": "Krunal",
      "email": "krunal@appdividend.com"
    }
  }
}

You can see that our described query data and fetching data are almost same, the return data is in JSON format with the data key.

Query Data

So, this is our first successful query to the GraphQL server. You can see that, we get only that data, which we have described. So that is it for this GraphQL Tutorial For Beginners.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.