0% found this document useful (0 votes)
14 views12 pages

GraphQL Test

GraphQL is an open-source server-side technology developed by Facebook to optimize RESTful API calls by allowing clients to request exactly the data they need in a single query. It offers advantages such as reduced data over-fetching, the ability to retrieve multiple resources in one request, and a strong type system that aids in debugging. The document also outlines steps to build a GraphQL server using Node.js, including setting up dependencies, creating schema and resolver files, and running the server.

Uploaded by

skekramskekram3
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views12 pages

GraphQL Test

GraphQL is an open-source server-side technology developed by Facebook to optimize RESTful API calls by allowing clients to request exactly the data they need in a single query. It offers advantages such as reduced data over-fetching, the ability to retrieve multiple resources in one request, and a strong type system that aids in debugging. The document also outlines steps to build a GraphQL server using Node.js, including setting up dependencies, creating schema and resolver files, and running the server.

Uploaded by

skekramskekram3
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

GraphQL

GraphQL is an open source server-side technology which was developed by


Facebook to optimize RESTful API calls. It is an execution engine and a data
query language.

Why GraphQL?

RESTful APIs follow clear and well-structured resource-oriented approach.

However, when the data gets more complex, the routes get longer. Sometimes
it is not possible to fetch data with a single request.

This is where GraphQL comes handy. GraphQL structures data in the form of a
graph with its powerful query syntax for traversing, retrieving, and modifying
data.

The following are advantages of using GraphQL query Language −

Ask for what you want − and get it

Send a GraphQL query to your API and get exactly what you need. GraphQL
queries always return predictable results. Applications using GraphQL are fast
and stable. Unlike Restful services, these applications can restrict data that
should be fetched from the server.

The following example will help you understand this better −

Let us consider a business object Student with the attributes id, firstName,
lastName and collegeName. Suppose a mobile application needs to fetch only
the firstName and id. If we design a REST endpoint like /api/v1/students, it will
end up fetching data for all the fields for a student object. This means, data is
over fetched by the RESTful service. This problem can be solved by using
GraphQL.

Consider the GraphQL query given below −

{
students {
id
firstName
}
Tamal Dey, Dept. of CA, PESU 1
}

This will return values only for the id and firstname fields. The query will not
fetch values for other attributes of the student object. The response of the
query illustrated above is as shown below −

{
"data": {
"students": [
{
"id": "S1001",
"firstName": "Mohtashim"
},
{
"id": "S1002",
"firstName": "Kannan"
}
]
}
}

Get many resources in a single request

GraphQL queries help to smoothly retrieve associated business objects, while


typical REST APIs require loading from multiple URLs. GraphQL APIs fetch all
the data your application need in a single request. Applications using GraphQL
can be quick even on slow mobile network connections.

Let us consider one more business object, College which has the attributes:
name and location. The Student business object has an association relationship
with the College object. If we were to use a REST API in order to fetch the
details of students and their college, we will end up making two requests to
the server like /api/v1/students and /api/v1/colleges. This will lead to under
fetching of data with each request. So mobile applications are forced to make
multiple calls to the server to get the desired data.

However, the mobile application can fetch details for both Student and College
objects in a single request by using GraphQL.

The following is a GraphQL query to fetch data −

Tamal Dey, Dept. of CA, PESU 2


{
students{
id
firstName
lastName
college{
name
location
}
}
}

The output of the above query contains exactly those fields we have requested
for as shown below −

{
"data": {
"students": [
{
"id": "S1001",
"firstName": "Mohtashim",
"lastName": "Mohammad",
"college": {
"name": "CUSAT",
"location": "Kerala"
}
},

{
"id": "S1002",
"firstName": "Kannan",
"lastName": "Sudhakaran",
"college": {
"name": "AMU",
"location": "Uttar Pradesh"
}
},

{
"id": "S1003",
"firstName": "Kiran",
Tamal Dey, Dept. of CA, PESU 3
"lastName": "Panigrahi",
"college": {
"name": "AMU",
"location": "Uttar Pradesh"
}
}
]
}
}

Describe what’s possible with a type system

GraphQL is strongly typed and the queries are based on fields and their
associated data types. If there is type mismatch in a GraphQL query, server
applications return clear and helpful error messages. This helps in smooth
debugging and easy detection of bugs by client applications. GraphQL also
provides client side libraries that can help in reducing explicit data conversion
and parsing.

An example of the Student and College data types is given below −

type Query {
students:[Student]
}
type Student {
id:ID!
firstName:String
lastName:String
fullName:String
college:College
}
type College {
id:ID!
name:String
location:String
rating:Float
students:[Student]
}

Move faster with powerful developer tools

Tamal Dey, Dept. of CA, PESU 4


GraphQL provides rich developer tools for documentation and testing queries.
GraphiQL is an excellent tool which generates documentation of the query and
its schema. It also gives a query editor to test GraphQL APIs and intelligent
code completion capability while building queries.

In this chapter, we will learn about the environmental setup for GraphQL. To
execute the examples in this tutorial you will need the following −

 A computer running Linux, macOS, or Windows.


 A web browser, preferably the latest version of Google Chrome.
 A recent version of [Link] installed. The latest LTS version is recommended.
 Visual Studio Code with extension GraphQL for VSCode installed or any code
editor of your choice.

How to Build a GraphQL server with Nodejs

We will go through a detailed step-wise approach to build GraphQL server with


Nodejs as shown below −

Step 1 − Verify Node and Npm Versions

After installing NodeJs, verify the version of node and npm using following
commands on the terminal −

C:\Users\Admin>node -v
v8.11.3

C:\Users\Admin>npm -v
5.6.0

Step 2 − Create a Project Folder and Open in VSCode

The root folder of project can be named as GraphQL.

Open the folder using visual studio code editor by using the instructions below

C:\Users\Admin>mkdir GraphQL
C:\Users\Admin>cd GraphQL
C:\Users\Admin\GraphQL>npm init --y

Tamal Dey, Dept. of CA, PESU 5


Step 3 − Create [Link] and Install the Dependencies

npm init -y (or npm init --yes): This command will generate a [Link] file
with default values without asking any questions.

Create a [Link] file which will contain all the dependencies of the
GraphQL server application.

{
"name": "graphql-demo",
"version": "1.0.0",
"main": "[Link]",
"type": "commonjs",
"scripts": {
"start": "node [Link]"
},
"dependencies": {
"@graphql-tools/schema": "^10.0.29",
"body-parser": "^2.2.0",
"cors": "^2.8.5",
"express": "^5.1.0",
"express-graphql": "^0.12.0",
"graphql": "^15.8.0"
}
}

Install the dependencies by using the command as given below −

C:\Users\Admin\GraphQL>npm install ______

Step 4 − Create Flat File Data in Data Folder

In this step, we use flat files to store and retrieve data. Create a folder data and
add two files [Link] and [Link].
Following is the [Link] file −
[
{
"id": "101",
"name": "ABC Engineering College",
"location": "Bangalore"
Tamal Dey, Dept. of CA, PESU 6
},
{
"id": "102",
"name": "National Science College",
"location": "Delhi"
}
]
Following is the [Link] file −
[
{
"id": "1",
"name": "Ajay",
"age": 20,
"major": "Computer Science",
"collegeId": "101"
},
{
"id": "2",
"name": "Vijay",
"age": 22,
"major": "Mathematics",
"collegeId": "102"
}
]

Step 5 − Create a Data Access Layer

We need to create a datastore that loads the data folder contents. In this case,
we need collection variables, students and colleges. Whenever the application
needs data, it makes use of these collection variables.

Create file [Link] with in the project folder as follows −

const fs = require('fs');
const path = require('path');

const load = (file) => {


Tamal Dey, Dept. of CA, PESU 7
try {
const filePath = [Link](__dirname, 'data', `${file}.json`);
const data = [Link](filePath, 'utf-8');
return [Link](data);
} catch (err) {
[Link](`Error loading ${file}:`, [Link]);
return [];
}
};

[Link] = {
students: load('students'),
colleges: load('colleges')
};

Step 6 − Create Schema File, [Link]

Create a schema file in the current project folder and add the following
contents −

type Query {
test: String

students: [Student]
student(id: ID!): Student

colleges: [College]
college(id: ID!): College
}

type Student {
id: ID!
name: String
age: Int
major: String
collegeId: ID
college: College
}

type College {

Tamal Dey, Dept. of CA, PESU 8


id: ID!
name: String
location: String
students: [Student]
}

Step 7 − Create Resolver File, [Link]

Create a resolver file in the current project folder and add the following
contents −

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

const Query = {
test: () => "Test Success, GraphQL server is up & running !!",

students: () => [Link],


student: (_, { id }) => [Link](s => [Link] === id),

colleges: () => [Link],


college: (_, { id }) => [Link](c => [Link] === id)
};

const Student = {
college: (parent) => [Link](c => [Link] === [Link])
};

const College = {
students: (parent) => [Link](s => [Link] === [Link])
};

[Link] = {
Query,
Student,
College
};

Step 8 − Create [Link] and Configure GraphQL

Create a server file and configure GraphQL as follows −

Tamal Dey, Dept. of CA, PESU 9


const bodyParser = require('body-parser');
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const app = express();
const port = [Link] || 9000;
const { makeExecutableSchema } = require('@graphql-tools/schema');
const { graphqlHTTP } = require('express-graphql');

// Load schema
const typeDefs = [Link]('./[Link]', 'utf-8');

// Load resolvers
const resolvers = require('./resolver');

// Create GraphQL schema


const schema = makeExecutableSchema({
typeDefs,
resolvers
});
// Middleware
[Link](cors());
[Link]([Link]());
// GraphQL Endpoint
[Link]('/graphql', graphqlHTTP({
schema,
graphiql: true
}));
// Start Server
[Link](port, () => {
[Link](`GraphQL Server running at [Link]
});

Step 9 − Run the Application and Test with GraphiQL

Verify the folder structure of project GraphQL as follows −

Tamal Dey, Dept. of CA, PESU 10


Run the command npm start as given below −

C:\Users\Admin\GraphQL>npm start

The server is running in 9000 port, so we can test the application using
GraphiQL tool. Open the browser and enter the URL
[Link] Type the following query in the editor –

Query-1

{
Test
}

The response from the server is given below −

{
"data": {
"test": "Test Success, GraphQL server is running !!"
}
}

Tamal Dey, Dept. of CA, PESU 11


Query-2

{
colleges {
id
name
}
}

Query-3

{
students{
id
name
}
}

Tamal Dey, Dept. of CA, PESU 12

You might also like