GraphQL: An Efficient alternative to REST

GraphQL: An Efficient alternative to REST Img
1 shares facebook twitter linkedin

GraphQL is a query language developed in 2012 specially for API. It provides a common interface between client and server for fetching data and various manipulations.

How it works differently?

Software Industry has seen an upsurge in the past few years. It is observed that most of the software applications, nowadays, require to fetch data from a server, where that data is stored in a database. Usually, it is the work of API to provide interface for data storage with respect to the application need.

One of the most popular ways to expose data from server is using REST.  When the REST concept was built, the applications were really simple. Hence, REST was a nice choice for many applications. But in recent years, the whole scenario of API has changed. The factors affecting the change includes increased mobile usage, availability of sundry frontend frameworks and demand of rapid feature development etc.

To address those factors, GraphQL was developed and open-sourced by Facebook. It is now available for all and is maintained by a large community of companies and individuals around the world.

GraphQL is not bound to any specific database technology or any storage engine. Rather, it is backed by the existing code or data. It is an API layer which is really flexible. You can use GraphQL for your existing backend code or data in order to rapidly develop products.

Note: GraphQL should not be confused as being a database technology. GraphQL is a query language specially built for APIs and not for databases.

Advantage of using GraphQL

1. Round-Trips are lesser in GraphQL

Using GraphQL has reduced the number of round-trips to call several functions; which were an issue while using REST. Moreover, a separate HTTP request-response cycle is there for each API; and to render even a single view between client and the server, the data fetching requires many round-trips.

While GraphQL is able to call several functions without the requirement of multiple round trips as it simply unifies data and create packages. The package data allows efficient delivery of data and require less number of resources for round trip calls.

2.  Client Specific Queries

The client seeks data through queries. Due to the usage of thin client by REST, the load of data processing increases on the server. Consequently, it is unbalanced even though there is a well defined client-server relationship.

GraphQL balances the data processing between the client and the server. This is done by simply specifying the expected data format to the client and accordingly structure data on the server side. This will enhance the performance as less number of resources are occupied in the processing of the query.

3. Self Discoverable

There are some specific implementations required by REST, therefore it has no self discoverability. Further, it requires to use the external solutions as it has no in-built documenting functionality. Even after using those external solutions, it has shortcomings.

On the contrary, GraphQL is self discoverable. It is based on relational database and queries are validated within GraphQL before the execution of the program. The feature of self description is significant for third party application compatibility.  Also, the self describing capability introduces the API easily to the users and the developers.

4. GraphQL is Hierarchical

GraphQL queries look exactly like the data they return i.e. the request and response are related. In other words, request can easily determine the response and the response can be used to make its request.

GraphQL on the server side just gives a specification to define various principles of design like hierarchy, code, type system among many more.

Why use GraphQL?

No versioning required:

One can easily add new fields and types to the API of GraphQL without influencing the existing code and queries. The apps will gain a continuous access to new features with the help of single evolving version provided by GraphQL. It encourages neat and maintainable server code.

Not constrained to one language:

GraphQL is not constrained to a particular computer language. It simply requires a specification  for the client and server. It is like any client can communicate with any server if they have a common language i.e GraphQL.

Use your own code, your own data:

GraphQL produces a uniform API for the entire application. It is not limited  to any particular storage engine. One can easily update the existing code with the help of GraphQL engines which are multilingual. Moreover, you can define functions for each field in the type system. It allows you to add your own data from a single endpoint. Hence, multiple endpoints are not needed.

Smart Content Fetching:

It is usually difficult to achieve a good cache hit rate for user specific content if we use HTTP cache methods. With the help of GraphQL schema one can have client side caching which know what is available and what is to be fetched.

Working of GraphQL

Process of GraphQL

GraphQL Describe your data

type Project {
name: String
tagline: String
contributors: [User]
}
Ask for what you want
{
project(name: "GraphQL") {
tagline
}
}
You can get desirable results
{
"project": {
"tagline": "A query language for APIs"
}
}

You can write two types of queries with GraphQL:

  • When you fetch (get)data from your server (Query).
  • While doing manipulations (create, update, delete)in your data (Mutation).
GraphQL queries

GraphQL queries are like JSON objects without properties:

{
"user": "name"
}
{
user {
name
}
}
GraphQL mutations

With GraphQL mutation you can manipulate data:

mutation updateUser($userId: String! $name: String!) {
updateUser(id: $userId name: $name) {
name
}
}

With this, you can manipulate your data and retrieve the response in the required format at the same time.

GraphQL through HTTP

You can send GraphQL queries through HTTP:

– GET for querying
– POST for mutation

GraphQL with Node.js

Steps to execute queries of GraphQL:

Step 1: To run server with graphql-server-express,install following package

Step 2: Then run “node server.js” with this code in server.js:

var express = require('express');
var bodyParser = require('body-parser');
var { graphqlExpress, graphiqlExpress } = require('graphql-server-express');
var { makeExecutableSchema } = require('graphql-tools');
var typeDefs = [`
type user {
id:ID
name: String
gender: String
}
type Query {
allUser: [user]
}
schema {
query: Query
}`];
var resolvers = {
Query: {
allUser(root) {
let user = [{
id: 1,
name: 'john',
gender: 'male'
}]
return user;
}
}
};
var schema = makeExecutableSchema({typeDefs, resolvers});
var app = express();
app.use('/graphql', bodyParser.json(), graphqlExpress({schema}));
app.use('/graphiql', graphiqlExpress({endpointURL: '/graphql'}));
app.listen(4000, () => console.log('Now browse to localhost:4000/graphiql'));

In this step we create schema, make query and return user detail from resolver on localhost:4000/graphiql.

Step 3: Your graphql server is running on localhost:4000/graphiql Go to graphql server and run following query for get all user.

Request:
query {
allUser {
id
name
}
}
Response:
{
"data": {
"allUser": [
{
"id": "1",
"name": "john"
}
]
}
}

Step 4: If you want to link “gender” resources without defining new API endpoints,

then simply add in your request query and you will get response with gender.

Request:
query {
allUser {
id
name
gender
}
}
Response:
{
"data": {
"allUser": [
{
"id": "1",
"name": "john"
"gender": "male"
}
]
}
}

You can write more queries and schema as per your need.

In Short:

This open source technology has been developed by Facebook and it was initially used in the native mobile apps. This technology was not known to many; until in 2015, when Facebook publicly spoke about GraphQL. Shortly after that they announced it to be available as open source. Though it was introduced at a conference on React.js, later on it was revealed that GraphQL is nowhere linked with React. Therefore, this technology is not limited only to be used with React.js but is open source, available for all.

1 Shares facebook twitter linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Hire Expert
WordPress Developers
Hire Now... Hire WordPress Developers