Home/Blog/Web Development/Deep dive into GraphQL: Benefits and applications
Home/Blog/Web Development/Deep dive into GraphQL: Benefits and applications

Deep dive into GraphQL: Benefits and applications

Awais Qasim
May 02, 2023
6 min read

What is GraphQL?#

GraphQL is an emerging, open-source data query and manipulation language for creating APIs. It also includes a runtime engine to fulfill the queries written in it. It was created in 2012 by Facebook to be used in their mobile applications as an alternative to the REST architecture. However, in 2015, they made it open source to target a larger audience.

What are the major benefits of GraphQL?#

What makes GraphQL efficient compared to commonly used REST architecture is that, in REST, data fetched using an API from a server, gets a response in the form of JSON, XML, or some other format. That data is filtered to retrieve the desired information. Chances are that, along with our requested data, there will be a lot of unwanted data that make the filtering process slow, or in the worst case, the server will need to be requested multiple times. The REST architecture works by creating multiple endpoints that correspond to different queries. Here’s an example of how that works. To find the computer science student in the sixth semester with the highest cumulative grade point average (CGPA), using the entities in the database shown below, first send a query like https://www.someweb.com/university in REST that will provide all the department's details. Then send a query like https://www.someweb.com/departments/<computer science dept id> that will provide the details of all the students in the department. Then send a query https://www.someweb.com/students/<student id> that will ultimately provide the details of the student with the highest CGPA. This is where the efficiency of GraphQL comes in handy. GraphQL allows specific data to be requested according to need. This provides more control on the client side. Another benefit of GraphQL is that it's not language dependent, and it specifies the method of fetching data from the server and manipulates it.

Comparison of GraphQL API vs. REST API
Comparison of GraphQL API vs. REST API

Learning GraphQL#

A basic working knowledge of JavaScript and ES6 is needed in order to get started in GraphQL. An application in GraphQL has two components, i.e., client side and server side. So having knowledge of Node.js will also be handy.

Basics of GraphQL#

The operations of GraphQL can be divided into two categories. When data is fetched from the server, a query is used, and when data is written on the server side, it's called a mutation. To fetch a record of a student entity with an id of 11401, a query can be written in the GraphQL client as shown below:

{
student(id: "11401") {
name
age
rollno
}
}

The response will be in the form given below:

{
"data": {
"student": {
"name": "Ali",
"age": "22",
"rollno": "201-CS-22"
}
}
}

A major point to be noted is that only the requested data returns. A student entity on the server side might have hundreds of attributes. In a normal REST API, the complete record against the id would have been received, but in this case, the query only listed three attributes to be fetched from the server, resulting in a fast response time.

Nested queries can even be used to get the required data in a single query. To retrieve the list of all course names that a student with id of 1234 is studying in a semester, the query can be written as shown below.

{
student(id: "1234") {
name
age
rollno
courses {
name
}
}
}

The response will be in the form given below:

"data": {
"student": {
"name": "Ali",
"age": "22",
"rollno": "201-CS-22"
"courses": [
{
"name": "Programming Fundamentals"
},
{
"name": "Discrete Mathematics"
},
{
"name": "Digital Logic Design"
},
{
"name": "Communication Skills and Report Writing"
}
]
}
}
}

The good thing is that since GraphQL saves the relationships between entities in the form of graphs, the query can be inverted too. In this case, to get the roll number (rollno) and name of all students studying the programming fundamentals course, the query can be written as follows:

{
courses(name: "Programming Fundamentals") {
name
student {
rollno
name
}
}
}

The response will be in the form given below:

{
"data": {
"courses": {
"name": "Programming Fundamentals",
"student": [
{
"rollno": "201-CS-22",
"name": "Ali"
},
{
"rollno": "245-CS-22",
"name": "John"
},
{
"rollno": "311-CS-22",
"name": "Smith"
}
]
}
}
}

Implementing the server side#

On the server side, these two functions need to be performed:

  • Create schemas for the entities to be saved.

  • Create functions that will understand the incoming queries and provide the necessary data. In GraphQL, these functions are called resolver functions.

While creating schemas, keep in mind what type of operations, like query/mutation, can be performed as an API on the server. However, schemas are just representations of data and have no way of defining where the data will come from. For that, resolver functions that act just like routers are needed. They will route the incoming requests to the backend. This is where another major benefit of GraphQL comes in handy—that it hides all the complexity from the client. The client will only see a single endpoint.

API routing and usage of resolver functions
API routing and usage of resolver functions

If an Express server is used, a simple schema of a student can be created, as shown below:

let schema = buildSchema(`
type Query {
student: String
}
`);

Here’s how to understand this schema. When the server receives a request for student, it will return a string. Now the resolver function needs to be defined. In this case, it returns a hard-coded name.

let root = {
student: function() {
return 'Ali Ahmed';
},
}

Here, a function has been created for the student endpoint, and it has returned a hard-coded name. This function is also wrapped in an object called root, though it’s not necessary to name it root. Since multiple queries might need to be implemented, it’s always advisable to wrap all functions in an object. For example, suppose there is data of university students in the database on the server. To find out how many students are enrolled in a specific degree, create a function for it. Information about all the departments in which there are more than a hundred students might be needed. Create a separate function for that.

let root = {
student: function() {
return 'Ali Ahmed';
},
department: function() {
return 'Computer science';
},
}

Finally, a new route to serve the GraphQL API needs to be created. In Express, the desired route can be created as shown below:

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

Here schema and rootValue refer to the schema root object created above. The visual tool graphiql tests if the API is working correctly.

The GraphQL endpoint is now ready to be tested. In this case, there is only one entity, student, in the API, so wrap it in braces, as shown below:

{
student
}

After executing the query, the response below is shown:

{
"data": {
"student": "Ali Ahmed"
}
}

This tutorial started with an introduction to GraphQL and then demonstrated the major GraphQL benefits. Then, the queries and mutations of GraphQL were listed. After creating some sample queries, a query was inverted to show that the result wouldn't differ due to the data relationships being saved as graphs. Then, the actions that need to be taken on the server side were detailed, i.e., creating schemas and resolver functions. Everything considered, it’s easy to conclude that the major benefit of using GraphQL is that there is no over-fetching of data from the server.

Your next learning steps#

To deepen your understanding and expertise of GraphQL, take a look through this selection of specialized courses on the Educative platform.

Building Full Stack Applications with GraphQL

A Practical Guide to GraphQL: From the Client Perspective

Building a GraphQL Endpoint with Deno

Getting Started with GraphQL using Node.js

Don't pass up this chance to increase your knowledge and expertise about GraphQL. Take the first step toward becoming a GraphQL expert by enrolling in Educative courses right away!


  

Free Resources