DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • What Is GraphQL?
  • Pagination in GraphQL: Efficiently Retrieve and Manipulate Data
  • Serverless Patterns: Web
  • Building REST API Backend Easily With Ballerina Language

Trending

  • Scaling Mobile App Performance: How We Cut Screen Load Time From 8s to 2s
  • Failure Handling Mechanisms in Microservices and Their Importance
  • My LLM Journey as a Software Engineer Exploring a New Domain
  • Solid Testing Strategies for Salesforce Releases
  1. DZone
  2. Data Engineering
  3. Databases
  4. Why and When to Use GraphQL

Why and When to Use GraphQL

For solutions to common REST query issues like overfetching and multiple network request, look to GraphQL.

By 
Hitesh Baldaniya user avatar
Hitesh Baldaniya
·
Updated Jul. 19, 21 · Review
Likes (14)
Comment
Save
Tweet
Share
120.6K Views

Join the DZone community and get the full member experience.

Join For Free

Image title

GraphQL solves some of the main REST API issues.

REST is an API design architecture, which, in the last few years, has become the norm for implementing web services. It uses HTTP to get data and perform various operations (POST, GET, PUT, and DELETE) in JSON format, allowing better and faster parsing of data.

However, like all great technologies, REST API comes with some downsides. Here are some of the most common ones:

  • It fetches all data, whether required or not (“over-fetching”).
  • It makes multiple network requests to get multiple resources.
  • Sometimes resources are dependent, which causes waterfall network requests.

To overcome these, Facebook developed GraphQL, an open-source data query and manipulation language for APIs.

You may also enjoy:  An Overview of GraphQL (Refcard)

Since then, GraphQL has gradually made its way into the mainstream and has become a new standard for API development.

GraphQL is a syntax for requesting data. It’s a query language for APIs. The beauty, however, lies in its simplicity. It lets you specify exactly what is needed, and then it fetches just that — nothing more, nothing less.

And it provides loads of other benefits.

This post covers some of the most compelling reasons to use GraphQL, and looks at some common scenarios where GraphQL is useful.

Why Use GraphQL?

Strongly-typed Schema

All the types (such as Boolean, String, Int, Float, ID, Scalar) supported by the API are specified in the schema in GraphQL Schema Definition Language (SDL), which helps determine the data that is available and the form it exists in. This, consequently, makes GraphQL less error-prone, and more validated, and provides auto-completion for supported IDE/editors.

No Over-Fetching or Under-Fetching

With GraphQL, developers can fetch only what is required. Nothing less, nothing more. This solves the issues that arise due to over-fetching and under-fetching.

Over-fetching happens when the response fetches more than what is required. Consider the example of a blog home page. It displays the list of all blog posts (just the title and URLs). However, to display this list, you need to fetch all the blog posts (along with body data, images, etc.) through the API, and then show only what is required, usually through UI code. This impacts the performance of your app and consumes more data, which is expensive for the user.

With GraphQL, you define the exact fields that you want to fetch (i.e., Title and URL, in this case), and it fetches the data of only these fields.

Under-fetching, on the other hand, is not fetching adequate data in a single API request. In this case, you need to make additional API requests to get related or referenced data. For instance, while displaying an individual blog post, you also need to fetch the referenced author’s entry, just so that you can display the author’s name and bio.

GraphQL handles this well. It lets you fetch all relevant data in a single query.

Saves Time and Bandwidth

GraphQL allows making multiple resources request in a single query call, which saves a lot of time and bandwidth by reducing the number of network round trips to the server. It also helps to save waterfall network requests, where you need to resolve dependent resources on previous requests. For example, consider a blog’s homepage where you need to display multiple widgets, such as recent posts, the most popular posts, categories, and featured posts. With REST architecture, displaying these would take at least five requests, while a similar scenario using GraphQL requires a single GraphQL request. Find out more with this book.

Schema Stitching for Combining Schemas

Schema stitching allows combining multiple, different schemas into a single schema. In a microservices architecture, where each microservice handles the business logic and data for a specific domain, this is very useful. Each microservice can define its own GraphQL schema, after which you’d use schema stitching to weave them into one that is accessed by the client.

Versioning Is Not Required

In REST architecture, developers create new versions (e.g., api.domain.com/v1/, api.domain.com/v2/) due to changes in resources or the request/response structure of the resources over time. Hence, maintaining versions is a common practice. With GraphQL, there is no need to maintain versions. The resource URL or address remains the same. You can add new fields and deprecate older fields. This approach is intuitive as the client receives a deprecation warning when querying a deprecated field.

Transform Fields and Resolve With Required Shape

A user can define an alias for fields, and each of the fields can be resolved into different values. Consider images transformation API, where a user wants to transform multiple types of images using GraphQL. The query looks like this:

query {
            images {
                        title
                        thumbnail: url(transformation: {width: 50, height: 50})
                        original: url,
                        low_quality: url(transformation: {quality: 50})
            file_size

content_type
  }
}


Apart from these reasons, there are a few other reasons why GraphQL works well for developers.

  • GraphIQl Editor or GraphQL Playground where entire API design for GraphQL will be represented* from the provided schema
  • GraphQL Ecosystem is growing fast. For example, Gatsby, the popular static site generator uses GraphQL along with React.
  • It’s easy to learn and implement GraphQL.
  • GraphQL is not limited to server-side; it can be used for frontend as well.

When to Use GraphQL

GraphQL works best for the following scenarios:

  • Apps for devices such as mobile phones, smartwatches, and IoT devices, where bandwidth usage matters.

  • Applications where nested data needs to be fetched in a single call.
    • For example, a blog or social networking platform where posts need to be fetched along with nested comments and commenters details.
  • Composite pattern, where application retrieves data from multiple, different storage APIs
    • For example, a dashboard that fetches data from multiple sources such as logging services, backends for consumption stats, third-party analytics tools to capture end-user interactions.

sample dashboard

  • Proxy pattern on client side; GraphQL can be added as an abstraction on an existing API, so that each end-user can specify response structure based on their needs.
    • For example, clients can create a GraphQL specification according to their needs on common API provided by FireBase as a backend service.

In this article, we examined how GraphQL is transforming the way apps are managed and why it’s the technology of the future. 

Further Reading

You Don't Need GraphQL



This article originally published here.

GraphQL Data (computing) API Schema Fetch (FTP client) Requests POST (HTTP) mobile app microservice End user Web Protocols

Opinions expressed by DZone contributors are their own.

Related

  • What Is GraphQL?
  • Pagination in GraphQL: Efficiently Retrieve and Manipulate Data
  • Serverless Patterns: Web
  • Building REST API Backend Easily With Ballerina Language

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!