Streamlining API Query Processes Using GraphQL and Apollo

Randolph Perkins
7 min readApr 26, 2021

In the software development arena, mastering server-side processes and the necessary steps to retrieving data via external APIs emerges gradually through hands-on experience. Fortunately, once many of the basic principles behind back-end development are apprehended, and setting up applications becomes more routine, there are numerous software tools available which facilitate in speeding up this process and allowing for more flexibility. GraphQL is such a tool, and functions as an improvement to the REST API standard in key respects. What follows is a brief introduction to the GraphQL query language, and its integration with the Apollo data graph paradigm, resulting in a useful approach to making API queries.

What is GraphQL?

GraphQL is a speedy and flexible query language and server-side runtime for APIs that excels at distilling predictable data from APIs, using whichever methods developers may prefer. It exists as an alternative to the well established REST framework, providing significant advantages in this respect. Developers can create schemas to describe all possible data that can be queried, made up of object types. Once queries come in, GraphQL will validate each query against the schema, only executing ones which have been validated. Each field in a given schema is attached to a function known as a resolver, which, during execution, is called to produce values.

What is significant in the query process is that, besides defining and validating syntax for API queries, GraphQL is unopinionated with respect to other decisions or directions relating to storing data or programming language used. Furthermore, no requirements are made for the network, pagination, or authorization. In the parlance of the CRUD model, the most often used GraphQL operations are queries and mutations, with queries functioning as a read operation, and mutations handling the three remaining operations, create, update, and delete.

Core Features and Advantages

The schema serves as the single source of truth for a GraphQL application. Calls to an API are handled in one round trip, and data types are strongly defined, reducing miscommunication. Due to the emphasis on types, a client may request a list of data types available, which aids in auto-generating documentation. There is also a variety of extensions available, many of which are open source and possess features not typically available with REST APIs. GraphQL, as mentioned above, is unopinionated in terms of specific application architecture. As a result of this, it can even work on top of an existing REST API, and may function using existing API management tools. It should be noted, however, that there is a slight learning curve for developers who are used to a REST API framework, particularly on the back-end, since much of the work related to queries is transferred to the server side.

Constructing A GraphQL Service

A good way to become acquainted with GraphQL is by analyzing its query and response structure. It is important to recognize that unlike REST APIs, which require loading data using multiple URLs, GraphQL retrieves all of the data an app needs in one request, and this works quickly even with slow mobile networks. This is due to the fact that GraphQL APIs rely on types and fields instead of endpoints. Thus one request, and one endpoint.

A simple example of generating a GraphQL service begins with defining types and fields, as well as the functions for each field. Here we will specify types for a logged in user and the user’s name, followed by their respective functions:

Once a service is running, it will receive the queries to validate and execute. Once checked, the GraphQL service will run the functions and return the result. Supposing the following query is entered:

We can see on the right that what is returned is a validated result, in JSON format.

Thus at its core, GraphQL works by asking for specific fields on passed in objects. In the above case, we simply asked for a particular name, which has a data type of string. But fields can take objects as well, which themselves may represent a sub-selection of fields.

Powerful Query Methods

The above example demonstrates the utility of traversing objects and their fields, and this feature alone would make GraphQL useful for grabbing data. Yet where the language truly excels is in its other methods for making queries. These include passing in arguments, using aliases, creating reusable units called fragments, and using dynamic values with variables. Furthermore, GraphQL contains features called directives, which are useful for specifying a particular instruction based on supplied arguments. And since cases may arise which necessitate modifying server-side data, the language includes features which are called mutations to carry out this task.

For purposes of this post, we will only touch on arguments. In a typical REST paradigm, one would only be able to pass in a single set of arguments, which include the URL slug and whichever query parameters are specified. With GraphQL, multiple API fetches may be undertaken, due to the fact that each field and nested object may have its own set of arguments. Arguments can be many different types, the language providing a default set, and the ability to declare custom types as well.

Drawing on the previous query example, we may specify a couple of enumeration type arguments which track a particular user’s id and their respective height in feet:

The JSON formatted response is rendered to the right.

GraphQL’s documentation provides thorough examples on the remaining query methods and their syntax. Utilizing these methods affords the developer quite a bit of flexibility with regard to writing highly specified queries all while using a minimum of API calls. These features, working in tandem with the Apollo framework, described below, represent the crux of GraphQL’s significant advantages over more traditional REST APIs.

Apollo Platform

Working with GraphQL, Apollo is a server framework which can undertake complex processes such as caching, data normalization, and UI rendering in a relatively straightforward way. The Apollo paradigm works via creation of a data graph, which is defined as a data layer that facilitates interactions with data from data stores and external APIs. This data graph resides between the client and back-end, and directs data flow, using GraphQL to enforce the structure of this flow. For this to work, the data graph requires a service to process GraphQL operations dictated by the clients, and then it would need to communicate with the back-end data sources, to fetch the specified data as required. All of this can be carried out via Apollo Server, which is an extensible, open-source JavaScript GraphQL server.

With Apollo Server, the developer can define a GraphQL schema, specifying the types and fields available in the data graph, as well as a collection of resolvers. The resolvers coordinate adding data from the back-end sources to each schema field. This server can be deployed in either a hosted or a server-less environment, and it supports many Node.js middleware options, as well as TypeScript.

The Apollo platform supports incremental adoption; thus as the schema expands and data sources increase Apollo Server can handle a larger proportion of requests, while existing request solutions can still be implemented aside the data graph. Apollo Server also has extension libraries which facilitate federation, which is when multiple services are used, each with their own GraphQL schema, instead of a monolithic server.

Apollo Client handles the front-end of the paradigm. Similar to Apollo Server, this is a customizable open-sourced JavaScript GraphQL client which possesses caching and state management features. Here queries may be defined directly within particular UI components. The cache can duplicate elements of the data graph specifically useful to the client, such that the client may query itself for data, with the obvious increase in performance resulting. While Apollo Client can work with many view layers, it has official support for React. For mobile apps, Apollo Client is supported with a Swift client for iOS and Java for Android.

Improvement of the Developer Experience

Adaptation of a wholly new set of frameworks will invariably come with a not insignificant learning curve. The Apollo/GraphQL paradigm is no exception to this. However, there is a wealth of documentation which accompanies these two frameworks, as well as an abundance of helpful demos and tutorials for integration into any software stack. Also, developers have the option to incrementally add their features, and in fact this approach is recommended by their publishers. Given the myriad advantages of GraphQL’s query methods, it would be unsurprising to see widespread adoption of the two frameworks in the near future. I hope this post has proven helpful in introducing alternative approaches to schema design and related principles, via the discussion of GraphQL and the Apollo platform. Thank you for reading!

--

--