GraphQL is an open source query language for APIs which can fetch data from multiple sources in one API call. It also acts as a server-side runtime to fulfil queries with existing data. GraphQL prioritizes giving the client only the requested data while still providing a complete API data description, and makes it easier to scale and evolve APIs.

Understanding GraphQL

GraphQL was designed with flexibility, speed, and developers in mind. With GraphQL, developers can build APIs however they see fit, then use a GraphQL specification to ensure the APIs are functional for clients.

One of the principal concepts of a GraphQL query is that the data you receive back is predictable. Rather than strings of surplus code, what’s returned is exactly what’s requested. This declarative data-fetching is especially useful on mobile devices, where bandwidth is limited. Apps that use GraphQL are also stable and fast because they control the data that’s requested and received, rather than the server. They’re also fast even on slow network connections, because a single request can return multiple requested items at once.

Building on GraphQL’s data simplification, APIs are organized by types and fields instead of endpoints. This means all data can be accessed at a single endpoint, enabling apps to ask only for what’s necessary. By reducing operational complexity, GraphQL fits into the workflow of a streamlined API connectivity solution.

A Brief History

In 2012, Meta (then Facebook) needed a data-fetching API that was powerful enough for its Facebook mobile applications. Led by Lee Byron, Facebook developed GraphQL as a way to simplify data fetching – specifically, from the perspective of product designers and developers. GraphQL was first used internally by Facebook, then publicly released and open sourced in 2015. Following the trajectory of many other open source projects, in 2019 the GraphQL project moved to its own GraphQL Foundation, hosted by the Linux Foundation.

GraphQL was designed as an alternative to the REST architecture. Standard REST APIs require loading information from multiple URLs via separate HTTP GET requests. With GraphQL APIs, all data is retrieved via a single POST request. While both REST and GraphQL return JSON-formatted responses, GraphQL is focused on streamlining and consolidating data.

How Does GraphQL Work?

GraphQL supports fine-grained data requests and gives clients more control over what information is sent. The client sends a GraphQL query in the form of a POST request to which the server returns a JSON-formatted response. GraphQL doesn’t require a specific application architecture, is deployable in multiple environments (including an integrated development environment [IDE]), and can be used with existing API management tools or on top of existing REST APIs.

Some key terms within GraphQL include:

  • Schema – Created by API developers to show what data clients are able to query, schemas are made up of object types which define what a client can request and the fields that represent the object’s characteristics.
  • Query – Queries are validated and then executed based on the schema. GraphQL cannot execute a query without defining an object type.
  • Resolver – Resolver functions attached to each schema field are called to produce a value in API execution. Resolvers are crucial architectural components of GraphQL.

One unique feature of GraphQL is that responses mirror the structure of the query (which is itself defined by the schema). This simplifies parsing for the client because the format of the server’s response is completely predictable.

Design

GraphQL’s hierarchical nature follows relationships between objects and works well in hierarchical user interfaces. It is also strongly typed, meaning each query level matches a type. Those types then define a set of fields. This is similar to SQL, where descriptive error messages are shown before completing a query.

Connect Resolvers to Data Sources

Resolvers are the key architectural modules that connect GraphQL fields, edges, mutations, queries, and subscriptions to data sources (and microservices).

You can learn how to build resolvers for AWS data sources in this GraphQL tutorial.

Specify What to Fetch

One thing that makes GraphQL queries unique is mirrored responses. Data returned from a query become predictable, because you know it will match the shape from the API request. When the returned data shape follows the client query, servers become simplified.

Pros of GraphQL

One major benefit of GraphQL is that extensions are available to provide features that are not available in REST. Other pros of GraphQL include the following.

Sets a Single Source of Truth

A GraphQL schema sets a single source of truth in GraphQL applications, providing a main location where all data is described. While the GraphQL schema is generally defined at the server, clients can still query and write data based on the schema.

No Overfetching

In REST architectures, overfetching can quickly become an issue: the application (backend) defines the data available for each resource and returns all of it in its response, even if the client (frontend) needs only a single element.  GraphQL calls happen in a single trip and give clients the requested data without any overfetching.

Improved Communication Between Client and Server

Because the data types are strongly defined, communication between client and server is clearer in GraphQL than REST. This underlying structure also means complex clients aren’t needed to call a GraphQL server. To learn more, and to see code-in-action, read about clients and servers on GraphQL’s official page.

Scalable with Federation

A set of design principles and tools, API Federation makes it conceivable to expose services within a bounded context as a consistent API for users, while also allowing services within that context to evolve without restrictions. GraphQL offers a method to federate the entire API and evolve without breaking previous queries, which is then scalable – and this scalability is one reason GraphQL is used by many enterprises.

Introspection

GraphQL’s introspective nature enables retrieving the GraphQL schema from a GraphQL API. Clients can also request a list of available data types, which is ideal for generating documentation automatically and for testing or retrieving schemas from multiple microservices.

Cons of GraphQL

While there are many reasons to adopt GraphQL, there are also a few downsides to be aware of. For instance, it’s not all out-of-the-box – special libraries are needed to consume someone else’s API. And, overall, GraphQL requires heavier tooling support than REST.

GraphQL’s cons compared to REST include the following.

Learning Curve

For developers accustomed to REST APIs, GraphQL comes with a steeper learning curve. It can also change workflow – API teams using GraphQL must also write maintainable GraphQL schemata. That said, if starting fresh, GraphQL can be easy to learn and use because requests and responses have the same structure.

Unique API Management Strategies

GraphQL might require new API management strategies, whereas REST APIs tend to fit into existing API management models. This is important to consider, as adding a new API management strategy can increase overall expense.

Complex Caching

Caching is less straightforward in GraphQL than it is in REST, where requests usually use an HTTP method (GET, POST, PUT, or DELETE). A standard GraphQL request is POST, which isn’t cacheable at the HTTP level. Caching can also get complex in GraphQL because having a single endpoint means that endpoint’s URL produces multiple, varying non-cacheable responses (good for fetching data, bad for caching). Server developers then end up differing queries, even though each operates within the same object. That all said, many GraphQL libraries offer caching mechanisms out of the box.