GraphQL vs REST APIs, and When to Use GraphQL
Before we continue discussing some of the core concepts in GraphQL, we'll take a bit of a tangent in this lesson to contrast and compare Github's existing REST API (v3) and their GraphQL API (v4).
Comparing Github's REST and GraphQL APIs
We'll dive into a good example that showcases GraphQL before we discuss and address some of GraphQL's core concepts.
We're going to use the Github Public API as this lesson's example. GitHub has two versions of its API currently active:
To access Github's REST API, we can make requests to the following public URL - https://api.github.com. This main parent route gives us an overview of all the different routes we can then interact with in the v3 REST API.
To explore GitHub’s GraphQL API, we can go to https://developer.github.com/v4/explorer. For this GraphQL interface to work, we'll need be logged in with a GitHub account.
For our first exercise, the first thing we'd look to do is to get the description of a particular repository with both the v3 and v4 APIs. The repository we'll be using is Github's own Hello World repository, created by the Octocat profile. The description we'll like to fetch for the Hello-World repository is
My first repository on GitHub!, which can be seen in the UI when we navigate to the repository route in our browser.
v4 REST API
When we head to https://github.com/octocat/Hello-World in our browser, we're presented with the information of the Hello-World repository in our UI. Github allows us to see the data being returned for this route by hitting the https://api.github.com/repos/octocat/Hello-World route. We're making a GET request here as well and the data returned looks as follows:
Though we've managed to retrieve the
description field we're looking for in the repository, the server sent us a lot more "useless" (i.e. useless for our current interest) such as the
name of the repository, details of the
owner of the repository, and other URLs that can allow us to make other requests to get more information. Regardless, we have to retrieve all this information despite the fact we only want the value of a single field.
v3 GraphQL API
Let's contrast this with GraphQL. We'll head over to the GraphQL Explorer GitHub provides for their new API at https://developer.github.com/v4/explorer. The first thing that can be noted here is that we're able to interact with an interactive environment to help make GraphQL requests. We'll talk about this a little more in the next lesson, but the capability of using IDEs is a cool feature that many different GraphQL services provide.