We're hiring! Check out open positions
Development

GraphQL vs REST - Is GraphQL The New API King?

Tim Davidson
11 min read

GraphQL is spoken about as the successor to REST APIs for good reason. It's not really fair to compare the two since they've been created with different intentions. Before we dive into the details, it's worth laying out a quick definition of what they both are and how they compare.

What's the difference between GraphQL and REST?

GraphQL is a query language for fetching data, specifically via API while REpresentational Transfer State (REST) is an architectural style for transferring data between computers on the web. 

REST was built in the early 2000s while web APIs were realising their potential as a way to standardise information transfer. Whereas GraphQL was created by Facebook in 2012 as a better way of fetching data across all their products and services.

What is REST, and why was it created?

REST is an architectural style for software that specifies a set of requirements for developing web services. It is intended for use with media components, data, or hardware devices. Here's a summary of why REST is hugely important to web technology:

  • It's used in a wide range of languages, frameworks and contexts.
  • It allows web apps written in multiple programming languages to connect with one another.
  • With the support of REST, web apps can run seamlessly in different operating systems like Windows and Linux.
  • Make can make user interfaces portable across platforms.

What is GraphQL and why did Facebook make it?

GraphQL is a server-side application layer technology developed by Facebook for query execution using existing data. It provides a declarative method of retrieving and modifying your data.

Unlike REST APIs, GraphQL allows data requests to be customised. The best way to think of this is needing to retrieve the name of a single Pokemon from a list of all Pokemon. Using REST, we'd have to request the entire list. Using GraphQL, we can specifically request the name of the Pokemon we need.

This specificity and flexibility of data requests was something that Facebook needed, given the magnitudes of data they deal with.

What Other Technologies are Using GraphQL?

REST has arguably been the standard for creating web APIs during the last decade. It includes several excellent concepts, such as stateless servers and organised resource access. However, REST APIs have proven to be too rigid to keep up with the continuously changing needs of the clients that use them.

GraphQL was created in response to the requirement for more flexibility and efficiency! It addresses many flaws and inefficiencies developers have while working with REST APIs. 

New technology like Gatsby uses GraphQL to allow page and StaticQuery components to define the data that they and their sub-components require. Then, as the components requires it, Gatsby makes that data available in the browser.

It's a difficult concept to articulate, but the idea is that GraphQL can be leveraged for elite performance on the web.

GraphQL Applications

The following are some of the most important uses of GraphQL:

  • GraphQL's customised queries can be used to improve application performance
  • It can be incredibly effective at simplifying complicated APIs.
  • Calls to REST APIs can be wrapped in GraphQL schema as a facade layer, which is useful when you need to combine data from several sources into a single API.
  • GraphQl is great for mobile applications where reduced bandwidth is a high priority

Fetching data with REST vs. GraphQL

REST APIs are used to fetch data by querying endpoints. 

For example on a simple social media platform, the /users/id> API might be used to retrieve user's details like name, user name, age, address, etc. Then there might be a /users/id>/posts endpoint for retrieving all of the posts they're written. Finally, /users/id>/followers, would return everyone who follows the user.

To retrieve the needed data via REST, you would need to send three queries to different endpoints. Depending on the kind of information we're looking to retrieve, chances are that we'll end up with a bunch of data we don't need.

By comparison, GraphQL allows the client to provide the exact data it needs in a query. A query could be submitted to the GraphQL server, which would return the data that matched the conditions of the query. 

The returned data is formatted as a JSON object, with a structure that matches the layered structure provided in the query.

Underfetching and n+1 problem

Underfetching and the n+1-requests problem are two further issues with REST APIs. Underfetching often indicates that a certain endpoint does not give sufficient information. To get all it needs, the client will have to submit more requests. This can lead to a scenario in which a client must first download a list of items before making one more request per element to retrieve the relevant data.

Consider how the same app would need to present the previous three followers per user. The API also includes the endpoint /users/user-id>/followers. The app will need to make one call to the /users endpoint and then hit the /users/user-id>/followers endpoint for each user in order to show the relevant information.

Overfetching -- Superfluous Data Downloads

Overfetching occurs when a client downloads more information than required. Consider a screen that needs to present a list of people just by their names. In a REST API, this app would typically call the /users endpoint and receive a JSON array containing user information. This response would typically contain other information on the returned users like their birthdays or addresses - information that is irrelevant and not needed.

Insightful Analytics on the backend

GraphQL provides detailed insights into the data requested on the backend. Because each customer defines exactly what information they want, it is easy to acquire a thorough insight into how the available data is used. This can aid in the evolution of an API by deprecating particular fields that any customers no longer require.

You can also use GraphQL to do low-level performance monitoring on your server's queries. To collect the data requested by a client, GraphQL employs the idea of resolver functions. The ability to instrument and measure the performance of these resolvers gives critical information regarding bottlenecks in your system.

Rapid Product Iterations on the Frontend

A common pattern with REST APIs is to organize the endpoints based on the views in your app. This is useful since it allows the client to obtain all necessary information for a certain view by just contacting the associated endpoint.

The main disadvantage of this method is that it does not allow for quick frontend iterations. Every modification to the UI increases the likelihood that more (or less) data is now required than before. As a result, the backend must be modified to accommodate the increased data requirements. This reduces productivity and makes it difficult to incorporate consumer feedback into a product.

This issue is handled with GraphQL. GraphQL's flexibility allows updates to be performed on the client without requiring additional work on the server. Because customers may declare their specific data requirements, no backend developer is required to make changes when the frontend design and data requirements change.

Advantages of GraphQL

Here are some highlighted benefits of GraphQL:

  • It offers declarative query language, which is not required.
  • Requests are tailored to your specific need.
  • It's hierarchical and product-focused.
  • GraphQL is a tightly typed language. It indicates that queries are run inside the context of a certain system.
  • Versioning is not required for API evolution.
  • It is suitable for fast application prototyping.
  • GraphQL queries are encoded in the client, not the server.
  • It automatically updates documentation in response to API changes.
  • It has all of the properties of the OSI model's application layer.
  • GraphQL provides a human-readable query.
  • It is simple to work with several databases with GraphQL.
  • GraphQL fields can be shared and reused at a higher component level.
  • It lets you choose which functions to expose and how they operate.
  • A single API request can be used to get data.
  • It aids in query batching and caching.

GraphQL OR REST?

It's okay to implement both REST and GraphQL on a project. However, here's a breakdown so you can see how they compare.

Resources

The resource is at the core of REST. Each resource is identifiable by a URL, and you may access it by making a GET request to that URL. You'll most likely get a JSON answer because that's what most APIs use these days. So it looks like this:

// GET /books/1
{
  "title": "Black Hole Blues",
  "author": {
    "firstName": "Janna",
    "lastName": "Levin"
  }
  // ... more fields here
}

One thing to keep in mind with REST is that the type, or form, of the resource and the method used to get it are inextricably linked. When discussing the above in REST documentation, you may refer to it as the "book endpoint." GraphQL differs in this regard since these two ideas are fully independent in GraphQL. You may have Book and Author types in your schema:

type Book {
  id: ID
  title: String
  published: Date
  price: String
  author: Author
}
type Author {
  id: ID
  firstName: String
  Lastname: String
  books: \[Book]
}

We've explained the types of data accessible, but that doesn't tell you anything about how those objects may be obtained from a client. One key distinction between REST and GraphQL is that the description of a resource is not dependent on how it is retrieved. To really retrieve a specific book or author, we need to add a Query type to our schema:

type Query {
  book(id: ID!): Book
  author(id: ID!): Author
}

Now, we can submit a request identical to the REST request previously, but this time with GraphQL:

// GET /graphql?query={ book(id: "1") { title, author { firstName } } }

{
  "title": "Black Hole Blues",
  "author": {
    "firstName": "Janna",
  }
}

We're finally getting someplace! Even though both may be queried through URL and both can provide the same structure of JSON answer, we can instantly identify a few differences between GraphQL and REST.

To begin, we can see that the URL with a GraphQL query indicates the resource we're looking for as well as which attributes we're interested in. Furthermore, rather than the server author selecting for us whether the linked author resource should be provided, the API consumer decides.

Most crucially, the identity of the resources, such as Books and Authors, is not linked to how they are retrieved. We may theoretically obtain the same Book using many different sorts of queries and data sets.

GraphQL Schema Vs. URL Routes

An API is useless if it is not predictable. When you consume an API, you're normally doing it as part of a program, and that program has to know what it may call and what it should anticipate as a response in order to act on that result.

As a result, one of the most critical components of an API is a description of what may be accessed. This is what you discover when you read the API documentation, and this information can be inspected programmatically using GraphQL introspection and REST API schema tools like Swagger. The API is often stated as a set of endpoints in today's REST APIs:

GET /books/:id
GET /authors/:id
GET /books/:id/comments
POST /books/:id/comments

So, the "shape" of the API may be described as linear --- there is a list of items you can access. When accessing or storing data, the first question to ask is, "which endpoint should I call?" As previously discussed, URLs are not used in GraphQL to identify what is available in the API. Rather, you employ a GraphQL schema:

type Query {
  book(id: ID!): Book
  author(id: ID!): Author
}
type Mutation {
  addComment(input: AddCommentInput): Comment
}
type Book { ... }
type Author { ... }
type Comment { ... }
input AddCommentInput { ... }

When compared to REST routes for comparable data collection, there are a few intriguing elements here. To begin, rather than sending a separate HTTP verb to the same URL to distinguish between a read and a write, GraphQL employs a distinct starting type --- Mutation vs. Query. With a keyword in a GraphQL document, you may specify the sort of action you're sending:

query { ... }
mutation { ... }

Other differences between REST Vs. GraphQL!

Let's look into some more differences for more understanding:

GraphQL

  • It is an application layer server-side technology that Facebook introduces for executing multiple queries with existing data.
  • You can organize GraphQL in terms of schema
  • GraphQL is relatively a fast-growing community
  • It follows client-driven architecture
  • It offers fast development speed
  • It has a separate identity from how far you fetch.
  • HraphQL offers you high consistency over all platforms
  • The server determines available resources in GraphQL.
  • A string should be the message format for GraphQL mutations
  • GraphQL partners require API customization
  • It is typed strongly
  • GraphQL endpoints are single.
  • It offers high-quality and consistent UX for all the operating systems (OS)
  • GraphQL uses metadata for query validation

REST

  • It is a software architecture style that defines a constraints' set for creating any web services.
  • It features server-driven architecture
  • REST is a huge community
  • REST has a relatively slower development speed.
  • You can arrange REST in terms of endpoints.
  • The message format in REST APIs mutations could be anything
  • REST API does not have machine-readable metadata cacheable.
  • It offers you a flexible public API that can enable new applications quickly.
  • It is very weakly typed
  • REST API has multiple endpoints.
  • It is much more difficult to get frequency and consistency over all the operating systems.

Is GraphQL an Underrated Query Language?

It will be difficult for someone who is new to GraphQL to put it up because its ecosystem and procedures are still evolving and developing. However, if one understands GraphQL, one may send simple text queries from the client application to request data from remote server-side apps to complete the task. Furthermore, tools like Apollo make caching and API creation easier. It handles caching cases on its own, without the requirement for specific code to enable it. On the other hand, file or picture uploading in GraphQL is still in its early stages, necessitating the use of a REST API.

Conclusion - We recommend GraphQL!

GraphQL has so many advantages over REST; it is faster compared to REST, allowing you to pick the fields you have to query quickly.

On a final note, selecting GraphQL or REST is a complicated task because both of them are good in their own ways. Moreover, they also feature some similarities, such as the list of fields in GraphQL and the endpoints in REST API.

Tim Davidson
Tim Davidson
Tim is the face of the company. When you want to kick off a new project, or an update on your existing project, Tim is your man. With a background in project management, Tim specialises in managing the chaos around the company.

Have an idea you want to discuss?

We’re based in Canberra, Australia and we LOVE working with locals… but we work with clients all around the world.

From the U.S. to the U.K. From Norway to New Zealand. Where there’s a problem to solve, we’ll be there!

More insights from us

Next.js vs Gatsby.js - Which Is The Best React Framework?
Development

Next.js vs Gatsby.js - Which Is The Best React Framework?

Next.js and Gatsby are two of the most popular static site generators used to build fast and SEO-friendly websites. They…
Tim Davidson
Tim Davidson
9 min read
The Pros and Cons of Headless Commerce - The Double Edged Sword
Development

The Pros and Cons of Headless Commerce - The Double Edged Sword

Our team recently jumped in to help a headless eCommerce project that was heading in the wrong direction. The team had…
Tim Davidson
Tim Davidson
11 min read
Next.js vs Nuxt.js - Is There A Clear Winner?
Development

Next.js vs Nuxt.js - Is There A Clear Winner?

Nuxt vs. Next: Which One Should You Use? When it comes to building scalable, interactive web applications, Nuxt and Next…
Tim Davidson
Tim Davidson
10 min read