# GraphQL

## Summary


Often when client apps wish to get data, they have to work with available REST APIs and live with their limitations. To obtain data, they make multiple API calls. In the process, they end up overfetching data and using only some of it. On slow connections, this dampens user experience.  

GraphQL is an alternative to traditional REST APIs but its not meant to replace REST.  You can describe your data with a well-defined GraphQL schema. Clients have the flexibility to get as much data as needed. While API calls are similar to querying databases, GraphQL is not a database language. GraphQL also interfaces nicely with frontend JavaScript frameworks such as React. 

GraphQL was created at Facebook and then open sourced. It's now managed by GraphQL Foundation.

## Discussion

### What exactly is GraphQL?

GraphQL is described as "a query language for APIs and a runtime for fulfilling those queries with your existing data". You describe your data using a schema. Clients then ask for exactly what they want and nothing more. Thus, control is with the client rather than the server. With SOAP or REST, clients had to work with well-defined endpoints, often making multiple calls to obtain a complete set of data. With GraphQL, a single API call is sufficient to do the same. 

GraphQL is not a database language. GraphQL is also not an implementation. It's an open source specification that can be implemented in any language. A GraphQL service sits between your app and the data. It provides a layer of abstraction. Based on a schema, it does validation on the queries and responses. It's APIs are based on types and fields, not endpoints. Clients no longer need to parse responses, since they get data in a form they want it. 


### Why do we need GraphQL when there's already REST API?

It's typical in REST to think of data as a resource. Each resource is exposed via an API endpoint. For example, data about a library would consists of books, authors, branch locations, members, staff, and so on. Each of these is typically exposed via its own endpoint. With GraphQL, the entire data is considered as a single interconnected graph of data points. What does this mean? 

Suppose you wish to know about books written by an author and the branches where these are available. With REST, we would need to make multiple queries since the information might come from multiple endpoints. With GraphQL, a single request is sufficient since relationships among books, authors and branches are all part of the same data graph. 

A book could be identified by a unique integer. GraphQL can validate this. Errors due to type mismatches are caught early by the GraphQL service instead of allowing applications to fail in unpredictable ways. GraphQL also has a feature called Subscriptions that makes it easier to update applications with real-time data. 


### Why does GraphQL treat my data as a graph?

GraphQL provides a layer of abstraction between the application and the data storage. In this abstraction, GraphQL models data as **nodes**. Connections among these nodes are **edges**. Thus, data is a graph of interconnected objects rather than resources accessed via multiple endpoints. We can call this the *application data graph*. 

Consider a library's catalogue of books. Books and authors are the nodes and they are interconnected. An author may have written multiple books. A book may have co-authors. If we query for a specific book and all its authors, GraphQL is basically extracting a subtree from the data graph. Let's note that a tree is also a graph but without any loops. 

A tree has a hierarchical structure. The beauty of GraphQL is that the query to obtain a subtree from the graph also has a similar tree structure. We can say that the query and its response have same data shape. This makes it easier to write queries and process the responses.


### What are the advantages of using GraphQL?

GraphQL is a specification. Implementations of the GraphQL server in various languages are available. Client implementations are also available to ease the developer's job. 

GraphQL does not impose how or where data should be stored. Data may come from multiple databases or REST APIs. There's no need to discard your existing REST API endpoints. GraphQL can work with them. In any case, GraphQL presents a single source of truth. GraphQL eliminates the need to build separate API endpoints for each type of client (web vs mobile). 

GraphQL eliminates the "chattiness" or the N+1 problem that's inherent in REST APIs. Another point of efficiency is that data is not overfetched. 

A UI component can obtain all the data is needs without worrying about how this maps to databases or multiple endpoints. Data fetching is declarative and UI-driven, which is also why many frontend frameworks (React, Angular, Vue) interface nicely with GraphQL. 

GraphQL is strongly typed. With **introspection**, we can retrieve GraphQL schema. Versioning like done in REST APIs is not needed. GraphQL API can be updated at field level. 


### What are the phases of a query in GraphQL?

A GraphQL has to be understood by a GraphQL service before it can respond with the correct data. A GraphQL service tokenizes the query string and then parses the tokens to build the Abstract Syntax Tree (AST). It then validates the query against the schema. If invalid, an error response is returned. If valid, the AST may be reduced to a form that's simpler to execute. If there are any defined query analyzers, they will be called. During execution, resolvers are called to obtain the actual data pertaining to each field.  

The GraphQL client is not part of the GraphQL specifications but clients simplify processing. Different clients handle the queries and responses differently. For example, Apollo Client normalizes the response and caches it. It also minimizes the original query for efficiency. 


### Could you briefly introduce common GraphQL terms?

Apollo Docs has published a handy GraphQL glossary. Another source is GraphQL's learning page. Here we describe some essential terms:

    + **Query**: A read-only operation to get data from a GraphQL service.
    + **Mutation**: While a query could be designed to do data writes, this is not recommended. An explicit mutation is recommended.
    + **Field**: The basic unit of data that we can obtain. GraphQL is in fact about selecting fields on objects.
    + **Fragment**: A set of fields that can be reused across multiple queries.
    + **Argument**: Every field and nested object can have an argument, thus enabling us to filter or customize the results.
    + **Alias**: To avoid naming conflicts in the results, aliases are useful. For instance, we can query the same object with different arguments and get the results in different aliases.
    + **Directive**: This can be attached to a field or fragment to dynamically affect the shape of data. Mandatory directives are `@include` and `@skip` to either include or skip a field based on a condition.

### What are some criticisms of GraphQL?

It's been said that REST can do what GraphQL does. Using JSON API, we can implement data-specific queries. Query parameters can filter data. JSON Schema can be used for type validation. OData can be used as a query language. These alternatives are better for small applications where GraphQL can be an overkill. GraphQL comes with the need to write resolvers. 

Error handling is more complex since the response has to be parsed. An error will be returned as a HTTP 200 OK status. This also means that we can't use monitoring tools that mostly ping an endpoint without a request body and look at only status codes. 

Unlike POST/PUT requests of REST, GraphQL can't do file uploading. 

REST calls conform to HTTP semantics and web caching is easier due to multiple endpoints. With GraphQL, given a single endpoint, web caching is harder to implement. Tools such as Relay or Dataloader can help. Apollo client-server implemented persisted GraphQL queries. 

Performance can be an issue since clients can construct complex queries. This is more so for data coming from third parties. With REST, an endpoint can be designed and fine tuned for a specific query. 

## Milestones

2012

Facebook's iOS and Android apps become native apps. These need an API to retrieve Facebook's News Feed. RESTful APIs and Facebook Query Language (FQL) are available but developers see a gap between what apps wanted and the queries that servers exposed. Developers had to write lot of code on server side to prepare data and on client side to consume it. It's to solve this problem that Nick Schrock of Facebook creates a first prototype called **SuperGraph**. This is renamed to **GraphQL**. 

2015

Facebook open sources GraphQL, which is also released as a draft specification. This move is partly influenced by Facebook's React that was open sourced in 2013, Facebook's React Native that's also open sourced in 2015 and Facebook's Relay that provides a framework for building mobile apps based on React, React Native and GraphQL.  

Jun  
2018

GraphQL specifications exits "Draft RFC" status. It defines *Type System Definition Language* and delivery of live data over GraphQL subscriptions. 

Nov  
2018

**GraphQL Foundation** is formed, to be hosted by the Linux Foundation. This paves the way for a vendor-neutral development of GraphQL. By now, GraphQL is being used by Airbnb, Audi, GitHub, Netflix, Shopify, Twitter, NY Times and many more. At Facebook alone, it powers billions of API calls every day. In March 2019, GraphQL Foundation announces collaboration with the Joint Development Foundation.