Blogs
Jason Smith
Chief User Experience Officer

Why Is GraphQL Replacing the REST API?

Sep 21, 2021
By: Jason Smith

Since its inception in 2015, GraphQL has soared in popularity. According to the State of JavaScript 2020 report, it was adopted by 47% of developers in 2020. This includes developers from large companies such as Starbucks, Paypal, and even Facebook.

As a result, many people now view GraphQL as a suitable alternative to REST API.

However, what exactly made GraphQL this popular? What makes it a powerful competitor to the often used REST API?

In this article, we will be discussing GraphQl and why it’s replacing REST as the API standard in the industry.

What is GraphQL?

Back in 2012, a little company called Facebook was trying to solve performance issues with their mobile applications over low network bandwidth. The standard REST API wasn’t going to cut it as they needed to reduce the amount of data moved back and forth in API calls.

As a result, Facebook created GraphQL: a query language and runtime API. GraphQL empowers the client-side alone to request as much data they need at a specific point in time.

To understand this better, let's have a look at a simple GraphQL query.

Query Output
 
{
    employee(id: "45911") {
        name
    }
}

{
    "data": {
        "employee": {
            "name": "Adrian"
        }
    }
}

As you can see, the above query and the result have the same form. Using GraphQL queries enables the server to know what the client has asked for. It also returns only the fields specifically requested.

Here is another example of a query where a related object (previous_employers) of the object (employee) is traversed to get back information in the same request:

Query Output
 
{
  employee(id: "45911") {
    name
    # Queries can have comments!
    previous_employers {
      name
    }
  }
}
 
{
  "data": {
    "employee": {
      "name": "Adrian",
      "previous_employers": [
        {
          "name": "Starbucks"
        },
        {
          "name": "Walmart"
        },
        {
          "name": "Costco"
        }
      ]
    }
  }
}

In addition to this, GraphQL has various other advantages, which we'll discuss further.

Read More: GraphQL - dotCMS Documentation

How does GraphQL work?

Take a look at the diagram below to get a better sense of the gears behind GraphQL.

GraphQL

The Architecture showcases how you can make ad-hoc queries to a single endpoint and access all the required data from various data sources.

Overall, GraphQL has its own type of system which can hide the complexities of third-party APIs, legacy infrastructure, complex databases, and any other type of backend data resource from the frontend apps. The API uses SDL (Schema definition language) to define schemas before queries run on its apps.

Read More: Using GraphQL to Simplify Headless Content Management

Why is GraphQL replacing REST APIs?

When REST API was designated as a standard, applications had to handle client to server or server to server communications between computers.

As technology has advanced, this way of computer communication has evolved drastically. mobile apps, IoT systems, and smart systems are examples of complex modern client-side systems. They communicate by using multiple resources in the backend along with numerous touchpoints to elicit a quick response.

Not only do they provide fast communication, but they are constantly changing based on the user requirements. Therefore, these systems need an API that has flexibility, efficiency, and scalability in order to be successful.

GraphQL is the best and currently the only solution that can fulfill their requirements. It offers a client-centric model for data fetching, which in turn speeds up the app.

Having REST API work on these complex client-side systems reduces the performance and increases the amount of coding needed.

GraphQL was developed to fulfill the need for more flexibility and efficiency—to ultimately excel where REST doesn’t. GraphQL solves REST’s weaknesses, especially in data fetching. In this case, you can simply send a single GraphQL query to the server with all the data requirements. The server then returns JSON with all the requirements fulfilled.

A single GraphQL operation supports a query (read), mutation (write), and the subscription to changes to data (continuous read) based on the schema. Once this operation information reaches the backend, it is interpreted against the whole GraphQL schema and fixed with the frontend data application.

For this main reason, GraphQL is now chosen over REST API for many apps.

What are some advantages of GraphQL over the REST API?

Avoid over and under fetching of data

GraphQL provides full control to the client-side to request only required fields. Its queries always return predictable results. This means that Apps using it are stable and quick. When using REST, REST API’s servers have complete control instead and often send back more than just the required fields.

Single Request Boosts Speed

GraphQL offers a single endpoint for calls to be handled between frontend and backend systems. This allows the application to run smoothly. GraphQL has its own type system, which allows you to couple the GraphQL server to servers and apps in any programming language or any type of database. In addition, with GraphQ: you can create as many new client apps as you need and make them communicate with the GraphQL server without caring about the backend servers. In the same way, you can connect as many backend servers of any form.

REST API has multiple endpoints. This means that numerous calls are made to fulfill most client requests. As a result, the application is slowed down.

You cannot achieve the speed of a single endpoint with REST API as it utilizes multiple endpoints and often additional coding efforts.

Powerful Developer Tools

Open-source GraphQL extensions are easily available to offer features not available with REST APIs.

By leveraging your API’s type system, you can build power-packed tools like GraphiQL with GraphQL. With REST API, such additional developments require coding from scratch, wasting valuable resources.

API evolution without versioning

The GraphQL API is quite supple in terms of data fields as well. You can add new fields without hindering the existing queries. Moreover, you can also hide and/or deter obsolete fields easily.

Since GraphQL uses a single evolving version of the API, it enables clean maintenance of server code and encourages access to new features without much effort. This reduces the issues caused in REST API by deprecation of calls.

GraphQL vs. REST: A Comparison

To further understand the differences between them, take a look at the following table:

Criteria GraphQL Rest
What are they? GraphQL is a new language for data query and manipulation of APIs REST API is an architecture to provide a communication system between computers (server and client)
Way to design Modern Standard
Architecture Supported Client-side Server-side
Organized by Schema and Type System Endpoints
Endpoints Single Multiple
Data Fetching Only specific data required by client fetched in single API call Data is over fetched or under fetched with multiple API calls
Performance Fast Slow comparatively due to multiple calls
Development Speed Quick Slow
Complexity in Learning Slightly Difficult Easy
Caching Via libraries (built on the top) Automatic
Community Growing day by day Large
Best Use Cases Multiple Microservice like IoT devices, Smartwatches and Mobile apps Resource driven apps, Simple apps

What do I need to know before starting with GraphQL?

Many beginners feel that GraphQL is too complex to learn and requires too many prerequisites. While it is easier if you know at least one or two front-end programming languages like React or Javascript or have experience with REST API, it is not mandatory.

In fact, you can begin learning with online courses. One example is Github. They have courses that provide hands-on experience with GraphQL.

Another option to learn the basics is the GraphQL foundation. They provide online training courses like Github does, as well as having dozens of helpful videos and blog posts. Unlike Github, the GraphQL foundation is cemented in the community. They have several live discussion and vendor channels that allow you to receive help quickly and accurately.

dotCMS and GraphQL

dotCMS is an easy way to gain support for your GraphQL APIs. dotCMS supports GraphQL in two primary ways:

  • Enables you to query your content repository
  • Provides an API that allows developers to query and return specific properties of content and shape the API response at call time.

dotCMS has tools that specifically help your graphql work better and be easier to use.

GraphQL API caching

dotCMS has a reputation for being a high-performance platform and during the go-live of a food & beverage chain in the US, we introduced a native caching layer specifically for GraphQL API calls, where average response times of GraphQL queries were dramatically reduced from 58 ms to under 4ms. Needless to say, if you have around 3 million visits per day, this will have an immediate impact on your underlying platform and infrastructure resources.

GraphQL Playground

dotCMS delivered a native built-in GraphQL Playground in release 21.05.1, which is a graphical, interactive in-browser GraphQL IDE that drives developer agility when building apps with dotCMS.

Future GraphQL improvements in dotCMS

In future releases, we’ll be exploring ways in which you can use dotCMS’s GraphQL support to perform ‘mutations.’ This will allow you to modify, update, and delete content with GraphQL query requests.

In addition, dotCMS plans to align the GraphQL APIs with the REST APIs and make sure that everything that can be done with REST, can also be done with GraphQL, and more. Building your next Digital Experience Platform with dotCMS will not be restricted in any way as we continue to support both flavors.

We’re excited that we embarked on the GraphQL journey and will continue to expand the GraphQL APIs and tooling for developers to make composable Digital Experiences Platforms (DXP) with the speed of light.

This video explains more about how to use GraphQL on dotCMS: Build and deploy your #Jamstack with #dotCMS, #NextJS and #GraphQL

Filed Under:

webinar

Build and deploy your Jamstack with NextJS and GraphQL

Take advantage of all the features of NextJS to build a top-notch SPA that has better performance, higher security, and scales quickly.

Watch Now

Recommended Reading

Headless CMS vs Hybrid CMS: How dotCMS Goes Beyond Headless

What’s the difference between a headless CMS and a hybrid CMS, and which one is best suited for an enterprise?

Exploring TimeMachine: How dotCMS Handles Content Versioning

With dotCMS, tools like TimeMachine and Workflow Management help enterprises control content versioning, content edits, user permissions, workflows and more.

Digital Ambition Requires Ambitious Technology

When it comes to the content foundation of a digital experience platform, critical capabilities are reasonably straightforward. There are only four, really - since security, scalability and containeri...