Fetching data from a GraphQL API using the Fetch API

Fetching data from a GraphQL API using the Fetch API

In this article we would be learning how to fetch data from a GraphQL API using javascript's fetch API. We would be querying github's rich API as our case study.

What is GraphQL?

GraphQL according to its official website is a query language for your API. It is a fascinating way to query or mutate data that is stored on the server. It brings a huge advantage of being able to get predictable data. Unlike with the REST API where requests to an endpoint returns all available data, you can make request for only the data you need, queries can also be nested to fetch data across relationships, this ensures speed and ease.

So, Let's dive in!

A typical request using the fetch() API looks like this

image.png

The params usually include our method, headers and the body of the request if any. Fetching from the github API means we would need a personal access token. Getting one is quite easy and you can find detailed steps here

Done grabbing your personal access token? Let's go!!

Now, we are onto the main course! Our request would be structured this way :

First we'll add our API endpoint

image.png

Next, we'll add our method and headers

image.png

Next, we'll add the body of our request

The body of our request will contain our query. A query to get our name and email would look like this :

image.png

Putting it all together, our fetch request would look like this:

image.png

We can handle the promise returned using then() or await

image.png

We now have our data and we can display or use it as we so wish!

We can also make queries for total number of repositories we have:

image.png

We can make more complex queries, like this:

image.png

This query will return data containing our name, email, total repositories we have and name, number of forks, time of last update and most used language for our first 20 repositories.

In this article, we have learnt that it is quite easy to work with a GraphQl API using a standard fetch method. You can leverage this knowledge to query other GraphQL APIs to build amazing projects.

You can continue exploring Github's GraphQL API here.