...

/

GraphQL: A Query Language for APIs

GraphQL: A Query Language for APIs

Learn how GraphQL is used to access multiple endpoints in a single query.

Introduction

Many client-server communication technologies have emerged over the years since the inception of the World Wide Web. Application programming interfaces (APIs) have further smoothed communication between clients and servers. In addition, coupled with emerging technologies, APIs have enabled the development of more complex applications. However, such advancements compelled API developers to invent newer methods for fetching data from the back-end servers due to the limitation of existing architectural styles. Although the preexisting REST APIs provide a scalable and flexible model for data transfer in the form of XML or JSON, they are insufficient to handle contemporary feature-rich and complex applications.

For example, today's social media applications like Facebook and Twitter fetch user data from multiple endpoints. Traditional architectural styles like the REST API prove inefficient for fetching data from multiple endpoints. Therefore, custom data-fetching solutions emerged with time. GraphQL is an example of such custom solutions. It was developed by Facebook to meet their exceeding data-fetching requirements.

Press + to interact
REST versus GraphQL: Accessing multiple endpoints
REST versus GraphQL: Accessing multiple endpoints

This lesson will introduce GraphQL and specify the essential components in client-server communication using the same. However, before that, we’ll identify some of the limitations of REST architecture that paved the way for GraphQL.

REST API drawbacks

In a REST API, we hit a URL and receive whatever data comes back. However, there are certain problems with how a REST API fetches data, as given below:

  • Multiple requests problem: A REST API sends multiple requests whenever data required by the application resides on multiple endpoints. There is a need for a mechanism to fetch data from multiple endpoints in a single request.

  • Overfetching and underfetching: Often, in a REST API, the data fetched in response to a single request is either a very large amount or a very small amount that does not serve the purpose of the application's request. Therefore, we need an approach to fetch the exact amount of data needed by an application.

Let's discuss these drawbacks in detail in the following sections.

Note: In this lesson, we’ll use SWAPI (Star Wars API) for demonstration purposes to convey better ideas of GraphQL to our learners.

Multiple requests problem

In a REST API, we fetch different types of data from different access points (URLs), which often causes us to send various requests to fetch the desired data. For example, to access the starships, planets, and films data using SWAPI, ...