Back to blog
Blog

What is GraphQL: A Comprehensive Guide

Kaya Ismail's avatar

Kaya Ismail

August 20, 2020

cover image

GraphQL CMS

Cosmic provides a GraphQL Headless CMS API to power content for your websites and apps.

The lack of standardization for APIs has been a challenge that software developers have faced for a long time. 

study by SmartBear found that 35% of API providers feel their documentation is poor or needs improvement. The problem is that inconsistent APIs increase the learning curve for developers and can slow development velocity. But perhaps poor API documentation is not entirely the fault of those doing the writing. 

GraphQL aims to solve the difficulties of API standardization and documentation with its straightforward querying language, technology-agnostic backend support, and self-documenting schema system. That’s why many development teams are opting for GraphQL over other API technologies that have a lack of widely-used industry standards.



While REST and GraphQL are both API paradigms that enable the sharing of data over the internet, there are some key differences developers should be aware of. Let’s take a deep-dive into GraphQL and whether it’s right for your project.


Getting to Grips with GraphQL? Here’s What You’ll Find in This Article:

  1. What is GraphQL?
  2. GraphQL vs REST
  3. Exploring Some GraphQL Benefits
  4. 3 GraphQL Examples: What is Graphql Used For?
  5. Is GraphQL Right For Your Project?


What is GraphQL?

GraphQL is an API querying language that is both language and database agnostic. That means developers can make standardized data queries to a GraphQL service without any knowledge of the backend implementation. Developers describe the data they need, and the API handles the task of fetching the appropriate data behind the scenes.

But let’s take a step back and examine the origins of GraphQL. 

In 2012, GraphQL began as an internal Facebook project led by co-creators Lee Byron, Nick Schrock, and Dan Schafer. Their aim was to build a better Facebook News Feed API:

“The three of us got to work trying to figure out how to build a better News Feed API and we just got super far down the rabbit hole,” Byron told Nordic APIs. “I think just a month or two of iterative improvements on what started as a prototype enfolding all of our ideas ended up being the first version of GraphQL.”

In 2015, Facebook publicly released GraphQL, and in 2018, the GraphQL project was moved from Facebook to the GraphQL Foundation, hosted by the Linux Foundation, a non-profit company.

Beyond the standardized querying language, GraphQL is a server-side runtime and type system. On the backend, a GraphQL service needs to be set up to validate and execute queries. This requires a schema that defines the object types and fields available and resolvers which handle the implementation details for retrieving the data on the backend.


GraphQL vs REST

GraphQL—similar to REST APIs—leverages HTTP to send and receive data. The key difference is that different REST requests are created based on HTTP methods and endpoints, while GraphQL queries are shaped within the JSON body of the request.

Cosmic GraphQL API

Cosmic GraphQL API. Click to zoom.

GraphQL Request
For example, take the body of this GraphQL request:

{
  person {
    firstName
    lastName
  }
}

With GraphQL, developers can define which data they want to get returned (first name and last name) by specifying each field within the object (person). The resulting response would look like this:

{
  "data": {
    "person": {
      "firstName": "John",
      "lastName": "Smith"
    }
  }
}

This results in another benefit that GraphQL has over REST is the ability to retrieve multiple resources through a single query, whereas REST requires a new query to be made for each resource.

The GraphQL response generally has the same structure as the request. Queries are interactive, so any changes to fields in the request body will dynamically change the response as well.

REST Request
This differs from REST APIs, which are based on resources. For example, here’s a similar request to a REST endpoint:

GET https://sample.com/person/1

In the case of REST, developers need to specify the location of the resource on the backend using the correct endpoint (/person) and path parameters (/1). The request body is blank because REST endpoints typically return all the data fields a resource contains.

The resulting JSON body could look something like this:

{
  "firstName": "John",
  "middleName": "Andrew",
  "lastName": "Smith",
  "email": "jas1992@gmail.com",
  "relationshipStatus": "single"
}

As you can see, REST APIs are much less flexible, and frontend developers have little control over the response they get back. The REST server returns what backend developers have decided the endpoint should give as a response.


Exploring Some GraphQL Benefits

If you’re still asking, “why use graphql over REST?”, read on.

There are a number of areas where GraphQL has the upper hand over most REST services.

Standardization: For one, GraphQL is simple to use. There’s no industry standard for REST APIs, so developers are forced to sift through documentation to understand any new API they need to use. With GraphQL, however, developers only need to learn the standardized querying language once, and they can work with any application or software that supports the technology.

Declarative: In addition, the ability to control the response from an API request enables developers to avoid over fetching or under fetching data. These situations waste bandwidth by providing more information than necessary or requiring multiple API calls to get all the data needed. GraphQL enables developers to pull all the required fields across multiple objects within a single request.

Self-documenting: Finally, GraphQL is introspective. That means the API is self-documenting and predictable for developers to use. Since the GraphQL server requires a pre-defined schema, developers can easily explore the data available using manual queries or a tool like  GraphiQL. With REST endpoints, it’s up to the backend developers to document any changes they make or leverage a tool like Swagger to generate the API documentation automatically.


3 GraphQL Examples: What is GraphQL Used For?

With the benefits of GraphQL clear, let’s look at some examples of several types of GraphQL queries. 

Pulling Data

When developers need to pull data from the backend, it’s typically called a GET request in REST terms. With GraphQL, these are queries that look like this:

query GetTitles {
  allBooks {
    books {
      # retrieves title of all books
      title
    } 
  }
}

GraphQL queries can be anonymous or named (GetTitles), and comments can be included using the # character. These features, and many others, helps to clarify what the query’s expected response should be. 

In this case, the response would be similar to this:

{
  "data": {
    "allBooks":  [
      {
        "title": "The Martian"
      },
      {
        "title": "The Great Gatsby"
      }
    ]
  }
}

Editing Data

If developers need to add, modify, or delete data, they’ll send a POST, PUT/PATCH, or DELETE request to a REST endpoint. With GraphQL, however, modifying data requires a mutation request. Here’s an example of creating a mutation:

mutation createBook(title: "The Old Man and the Sea", author: "Ernest Hemingway") { }

This simple mutation will create a new book object on the backend with the specified title and author. If the mutation was successful, we’d get a response that includes a unique identifier for the new data object created on the backend.

{ "data": { "createBook": "sqdYsdf" } }

As with queries, developers can shape the responses they get from mutations. For example, it’s possible to request certain fields to be included in the response along with the unique identifier, such as the title, author, or date created.

Subscriptions

Along with simple queries and mutations, GraphQL supports subscriptions , which enable a frontend app to retrieve real-time data updates from the server. 

For example, if a frontend app needed to keep a running list of books as they’re added to its database, developers could set up a subscription event using the following request:

subscription {
  new_books {
    id
    title
    author
    date_added
  }
}

Once the subscription is set up, the server will automatically push new data to the frontend. The responses will include all the fields in the initial subscription request. 

It’s important to note that subscriptions are sent to a websocket endpoint because HTTP connections typically close once a response is returned. Instead, the websocket connection, and in turn, subscription remains open until the frontend requests to unsubscribe or an error occurs. 

Without subscriptions, it’s incredibly difficult to build real-time functionality. It often requires an approach called polling, which involves sending periodic requests to an API. But this approach is inefficient and could risk hitting request limits. Subscriptions, therefore, are a powerful way to ensure frontend applications receive data updates in real-time without requiring polling.


Is GraphQL Right For Your Project?

While GraphQL adoption is growing, many development teams still opt for REST APIs when integrating new frontends with their CMS because it’s an API paradigm they’ve been familiar with for a while. GraphQL, however, is ideal for simplifying development, reducing bandwidth usage, and reducing the time-to-market for content-driven apps. In the end, either technology can fuel static site generators, mobile apps, websites, and more.

The good news is that with Cosmic you don’t need to choose between REST and GraphQL . The headless CMS supports both technologies, so brands can launch content-rich apps faster, without worrying about backend compatibility. And if you're not quite ready to make the change to GraphQL, Cosmic’s REST API also supports a GraphQL-like feature that allows you to declare what properties are returned with the response using  "props".

Consider Cosmic to fuel your digital experiences, and check out our GraphQL-driven demos.