What is GraphQL API?
GraphQL is an open source data query and manipulation language originally developed and released by Facebook in 2012. It was developed by Facebook to help them rebuild their native mobile applications and because they needed "a data-fetching API powerful enough to describe all of Facebook, yet simple enough to be easy to learn and use by our product developers".
GraphQL has since been made open source in 2015 and is now governed by the GraphQL Foundation to ensure its development will happen in an open and neutral way.
Although GraphQL was initially developed specifically for mobile applications, its use has since spread into all types of development as an alternative to using REST APIs. It gives the client application the power to define and structure the data needed which greatly reduces the number of API calls as well as makes sure that the returned data is structured and only contains the information requested.
Basically, with GraphQL, you make sure your platform retrieve exactly what is needed from the server. Nothing more, nothing less.
We're talking more control over what you retrieve, and more flexbility on what you can do.
How does GraphQL work?
The best way to explain how GraphQL works is by comparing it to the regular workflow of retrieving data through a REST API. Let's use the original case of Facebook's mobile app and building the News feed as an example.
To build the News Feed, Facebook realised they needed to retrieve a lot of data from multiple sources in order to build it. And this made the team face 2 challenges:
- It was slow to query the data
- Each request required data from multiple different sources
Firstly, to build the News Feed they needed all kinds of data to be displayed: The name of the one posting, their image, the post itself and any image or video shared. And that's without even getting into including post likes, comments and the names and profile pictures of those who like it.
Querying all of this data meant that the mobile app was quite slow, and thus they'd need to load it in different stages if they wanted to improve performance: an initial load with only the post itself and then another with richer data such as likes. To accomplish that they'd need at least 2 endpoints all of a sudden.
And while that could be manageable, it only got worse when it came to the second challenge: all of the data wasn't in one single place to begin with. So even just the simplest of queries would have to be sent to various different sources and databases before it could even be assembled to the finished view in the app.
So how does GraphQL solve this problem?
Imagine the situation above, where we have a single client querying data to multiple endpoints to gather the resources needed. This works in 2 separated layers: one making the query and one delivering the data.
Enter another layer in-between: GraphQL.
Instead of sending multiple requests directly to the data sources, the client will now send a combined (and potentially complex) query to the GraphQL endpoint and it will handle the rest. It will make sure to fetch the data requested by the client and return it in a structured output that is easy to use.
Compared to using custom-built REST APIs, GraphQL essentially helps you in not over-fetching data - and then you don’t have to spend time on building APIs for all the different combinations of the content you need to retrieve.
By fetching just the right data sets, your application/website becomes faster for your visitors and they won’t have to pay for excessive data use when visiting your app or website. This makes GraphQL not just a beneficial feature for developers, but also for your visitors and your business in general.
The GraphQL building blocks
To understand - and start using - GraphQL there are two main building blocks that are important to look at: Schema and queries.
Let's go through them separately first and then show you video showing you how the two are combined in a GraphQL service.
The typed schema system used in GraphQL is what makes everything it does possible. GraphQL query language is all about selecting fields on objects that you want to query. And to make it work across any backend framework and programming language, it needs to have its own rules for how queries are handled and what data can be returned.
Once you start working with GraphQL queries you'll notice that a query closely matches the result and that it becomes quite easy to predict what the query will return - even if you don't know much about the GraphQL server itself.
To keep it all structured, the GraphQL service that handles the queries will have a fixed set of types that describe the set of possible data that is available to query. That way, whenever you make a query, it will be validated against this schema and only be executed if it is a valid query.
While the data you can query will depend on the GraphQL service you're using, it'll always be predictable and follow this structure of objects and fields.
You can get more familiar with the Schema in the official documentation.
Queries is what it's all about with GraphQL. At its core it's all about asking your service to return specific fields on objects that you select. If we look at an example of a simple query in Umbraco Heartcore, we'll see that the result of the query is the same shape as the query itself.
This is essential to GraphQL, as it gives you two large benefits:
- You always get the result that you expect
- The server knows exactly what data you want to see
The first benefit is great because it helps you predict what data you'll receive as well as the structure. Knowing this, it'll be much simpler for you to handle the data the server returns and have it consumable by the application you're sending the data to.
The second benefit comes from the typed Schema system described in the previous section. By having a clear structure of possible objects and fields that can be queried, the server will always know what it's supposed to return. And if there's ever an error in the query, it won't be validated and the user will be prompted with a descriptive error message that enables fast troubleshooting.
Putting Schema and Queries together
In the video you can see how a simple query works and the data it returns in a nice and predictable structure.
And if you're unsure of which objects and fields you can query, you can open up the Schema directly in the service and see everything that is valid. This includes the scalar types of each field, so you know the format of data that can be returned. GraphQL comes with 5 default scalar types (Int, Float, String, Boolean and ID), but can be customized to include additional fields (eg. Date).
Pros and cons of GraphQL
Should everyone use GraphQL? Not necessarily.
While GraphQL has some clear advantages compared to traditional REST API queries, it's not always necessary for your project. In fact, for some projects it wouldn't give any real benefit to make the switch. Below we've listed the main pros and cons of GraphQL.
Pros of using GraphQL
All in a single request
Say goodbye to overfetching - get it right the first time. With total control in defining and structuring each query and the hierarchical nature of GraphQL, you’re guaranteed to get exactly the content you need in one round trip. That means more spare time to give your solution some extra oomph.
Keeping the volume of data transfer lower also means a faster connection and better loading times for your clients. We’re sure that app developers will appreciate this one!
GraphQL is strongly typed and thus creates descriptive error message in the backend when something goes wrong. This saves you tracking down the source of the issue yourself and gets you faster back on track with your queries.
So bring on the typos!
Creative freedom - without language limits
Don't worry about the stress of re-training developers - GraphQL can be used in any language (so long as it can make HTTP requests). If you're lucky enough to have a CMS with client libraries that opens up even more doors.
On top of that, there's no need for front-end developers to wait around for an endpoint from a back-end developer. With GraphQL you can get straight to it. Plus, you can tailor your queries to retrieve exactly the content you need to render.
GraphQL is introspective
Querying for the right data requires you to know what's on the server. Luckily, this is easy with GraphQL as you can simple ask it!
With GraphQL you can get a list of types it supports, which creates a powerful and intuitive platform to work with. On top of that, documentation becomes much faster as you can use it to auto-generate the documentation.
Cons of using GraphQL
Complexity for server developers
For it to be so easy for the client and the user, doesn’t that mean there’s an extra workload somewhere else? Yes, it does.
With GraphQL, the more complex queries mean more processing work for the server. This means server developers will need to be on top of more, and will increase the complexity of the server setup.
A lot of this can be alleviated by using managed services, but this will still add extra moving parts to the server setup that needs to be managed to some degree.
More work to manage and maintain the API
With the GraphQL API it also adds extra work to manage and maintain. And depending on how it's implemented it might also require different API management strategies to account for rate limits and pricing.
If you're maintaining your own API this will also mean that you need to write and update GraphQL schema.
In a lot of cases the benefits of using GraphQL will outweigh the extra work required, but it can require resources that a company does not have.
Luckily there are services out there that takes care of this for you. An example is out headless CMS, Umbraco Heartcore, where those hefty tasks are taken care of for you.
GraphQL is (yet) another new thing to learn
GraphQL doesn't require you to learn a new programming language or framework, which means it doesn't require developers to learn completely new skills.
But it does still have a learning curve and that will take time, even for developers familiar with REST APIs. If you're going to maintain and manage the API itself, that will also add a layer of complexity.
Luckily GraphQL is very intuitive and with its introspective nature and strongly typed error messages, a lot of the learning will come from simply using it.
But if you've yet to meet any performance issues or limitations of using REST APIs for your applications and websites, then it might not be worth it to learn and use.
Want to see how GraphQL makes your life easier?
Try out the GraphQL Playground in our headless CMS to see how it all works.
Click the button below to take a 14-day trial and see for yourself!