The API KnowledgeShare

Aloi's guide to APIs for technical and non-technical users.

GraphQL

The increasing demand for real-time and big data has proven to be too much for the REST architecture. While it has solved a lot of the issues in the past decade, it is now time for a new paradigm to handle modern data requirements.

GraphQL has proven to be a strong API technology contender in filling the gaps with the REST framework. It provides sophisticated methods of consuming data so that you can retrieve only the data you desire to consume from an application. From its humble beginnings at Facebook, it has now evolved into a new standard for developing APIs for both web and mobile applications.

Let’s take a look at GraphQL and why companies like Github, Shopify, Coursera, and Yelp are quick to adopt this technology.

What is GraphQL?

Contrary to what the name implies, GraphQL is not a query language for graph databases. However, it does embody the concepts of “graphs” and “query language” in its uses. It is a query language and runtime environment for creating APIs and adopts the framework of a single graph of data for an API. GraphQL is a form of specification in building APIs using various libraries and tools.

The “graph” part of the name refers to the data model that GraphQL uses to work with application data. A graph is a data model where entities or objects are connected by links. These objects are somehow related to each other which builds a web. Humans intuitively think of data as related to one another; thus making it easier to develop APIs using the graph as a data model.

What Can GraphQL Do For You?

GraphQL solves many issues arising from the use of REST architecture. However, instead of developing a patchwork of solutions, it creates a new paradigm for building APIs which brings various benefits. That said, GraphQL can be utilized with RESTful APIs — this is at the core of Aloi’s offering.

Below are some highlights of GraphQL’s benefits:

  • Efficient data fetching. Using GraphQL queries, applications can define what data is needed all in one request. It should expect to receive the exact set of data queried in a request. That means no underfetching or overfetching occurs. As a result, it reduces the number of requests which improves application speed.
  • Schema system. When creating an API under GraphQL, it requires a user-defined schema which should follow a strict type system. This schema serves as a blueprint for the data handled by the API. It allows the application developers to determine what data is available and in what format.
  • Independence from data services. GraphQL works with any database implementation. That means a single request from the API can pull data from various sources.

A Quick GraphQL Example

Consider the following GraphQL schema:

GraphQL Schema

Above, we define a Book type with the relevant fields including a query, booksByTitle. The query takes two required arguments which are indicated by the exclamation point. Also, it returns an array of Book objects

Note the role of fields in defining the Book type. These fields are units of data that are also used in queries. In return, the exact fields also appear in the JSON response data. Consider the following query:

API Query

The query is asking booksByTitle for three books with “Harry” in their titles. Additionally, the query defines the structure of the data it wants by indicating the fields title and year. The resulting data may look like as follows (in JSON):

JSON Format

Operation Types

GraphQL features three operation concepts: query, mutation, and subscription. In the API, these three operations are executed concurrently if the requests are received at the same time. A well designed GraphQL API does not typically follow the top-down control flow but will execute operations as it receives them. That means API connections are more dynamic compared to REST.

Query

A query is a basic entry point to a GraphQL API. A simple query is often composed of fields, arguments, or variables which outline the requested data from the API.

Let us extend the schema from the previous section:

Schema

We can request a list of books including the relevant title, ISBN, and year for each entry.

API Object Book

The resulting list may look like as follows:

API Data Result

As shown, the resulting data takes the form of the fields defined in the query.

On the other hand, arguments can also be passed to the queries. It can be required (indicated by an exclamation point) or optional. In cases where arguments are optional, default values must be declared.

As such, in the above schema, we can query the API by:

Schema

Just like the previous section, we will receive three books with the term “Harry” (which is passed as a title argument) because the limit has a default value of 3 in the schema.

Variables can be used to avoid injection attacks by string interpolation through user-generated content. To use variables, they must be declared first. Then, the declared variables can be used in the query. Finally, a key-value pair is passed along with the query. For example, we can modify the above query to use variables.

API Query

Then, the key-value pair is as follows:

with Key-value pair

Mutation

If queries can request data, GraphQL mutations update data. Thus, it provides another entry-point into the API. First, mutations should be defined in the schema.

Extending our previous schema, we can add a BookRating type and a mutation that accepts new ratings for the books on the database.

GraphQL Schema BookRating

Note that the mutation returns a BookRating object which includes a Book object. That means we can access any of the fields on Book. Hence, we can send the following mutation:

GraphQL Schema BookRating Object

Which should return the following data:

GraphQL Schema Data Result

Subscription

Aside from requesting data using queries and updating data using mutations, GraphQL subscriptions allow applications to receive real-time data from the API. It is a way to push data from the server to the clients without having to send requests every time.

Subscriptions are similar to queries where you specify the fields that you require. However, instead of receiving the requested data right away, the result is sent every time a relevant event happens on the server.

From our example above, we can create a subscription that will send a new book review to the client every time a rating is made.

API Subscription

A subscription query may look like this:

API subscription query

GraphQL Schema

Since the beginning of this article, you have been dealing with GraphQL schema. As shown, it is essentially a data model from which queries, mutations, and subscriptions are based on. It is the core of any GraphQL server implementation that describes functionalities available to the client and how to connect to it.

A basic schema can be composed of object types, scalar types, query types, mutation types, and subscription types. The last three types are described and shown in the last section.

Object types are data units composed of properties we know as fields. These objects can be fetched by applications including their fields. From our recurring example, the following is a Book object:

API Book Object

Each field is defined by a scalar type which can be in ID, Int, Float, String, or Boolean.

Query types, mutation types, and subscription types are entry-points in the schema that allow the application to request for data, update data, and wait for real-time data. To review each type, you can go back to the previous section and examine the schema described in each operation.

What is GraphiQL?

There are various tools to test and learn GraphQL. One of the most popular is GraphiQL which is an in-browser GraphQL IDE. It allows viewing of schema through introspection, variable definition, query validation and autocompletion.

GraphiQL is an official project under GraphQL Foundation available in the GraphQL repository.

GraphQL repository

How Does Aloi Use GraphQL?

Aloi allows you to deploy RESTful APIs and connect them to one another using GraphQL. Integrating APIs have historically been tedious in mapping REST requests and responses to one another in an asynchronous fashion. Fetching only the data you want from two given APIs isn’t possible with REST alone. By deploying APIs on Aloi, you can query the data from any of the applications you want to connect in any way that you want on a uniform interface. GraphiQL allows you to see data from applications simultaneously while mapping and transforming data across services. Once the query is complete, you can deploy it on Aloi to run your integrations.