How to use fetch API to call GraphQL APIs?

Fri Mar 31 2023

4 min read

GraphQL is a powerful query language allowing developers to retrieve and manipulate data from APIs efficiently.

While there are many ways to access GraphQL APIs, using the Fetch API can make the process smoother and easier to manage.

Basic concepts

GraphQL is a query language and runtime that allows developers to retrieve and manipulate data from APIs efficiently and flexibly. On the other hand, the Fetch API is a modern browser API for making HTTP requests from JavaScript.

Using the Fetch API to call GraphQL APIs, developers can take advantage of its features like asynchronous requests and error handling.

Writing a GraphQL query

When working with GraphQL APIs, the first step is to write a GraphQL query that specifies the data you want to retrieve. A GraphQL query is composed of a series of fields that represents the shape of the data.

The basic structure of a GraphQL query looks like this:

graphql
query {
field1
field2 {
subfield1
subfield2
}
field3
}

In this example, field1, field2, and field3 are all top-level fields you want to retrieve. field2 comprises two subfields, subfield1 and subfield2.

Using the Fetch API to Call a GraphQL API

Let’s make an API call to an actual GraphQL API. For this purpose, we will use the GeoDB Cities GraphQL API from Rapid API Hub.

Loading component...

Step #1: Create a Request object with the GraphQL query

To create a Request object with the GraphQL query, you need two things, i.e., API endpoint and options objects. The options object will contain the HTTP POST request method along with additional headers and a request body. The request body will be the GraphQL query that we will send to the server.

js
const url = 'https://geodb-cities-graphql.p.rapidapi.com/';
const query = {`
countries(namePrefix: "America") {
edges {
node {
name
capital
flagImageUri
currencyCodes
}
}
}
}`;
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-rapidapi-host': 'geodb-cities-graphql.p.rapidapi.com',
'x-rapidapi-key': 'YOUR_RAPIDAPI_KEY' // replace with your RapidAPI key
},
body: JSON.stringify({query})
};
const request = new Request(url, options);

Step #2: Send the request using the fetch() method:

Once you have created the Request object with the GraphQL query, you can send it to the server using the fetch() method. The fetch() method returns a Promise that resolves to the Response object from the server.

js
fetch(request)
.then(response => {
// handle the response from the server
})
.catch(error => {
console.error('Error:', error);
});

Step #3: Handling the response from the server:

The Response object from the server will contain the data returned by the GraphQL query, along with any errors that may have occurred. To handle the response, you can call the json() method on the Response object to parse the response body as JSON. This will return a Promise that resolves to the parsed JSON data.

js
fetch(request)
.then(response => {
return response.json();
})
.then(data => {
console.log('Data:', data);
})
.catch(error => {
console.error('Error:', error);
});

Here's a complete code example that you can use to test calling the GeoDB Cities GraphQL API using the Fetch API:

html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>GraphQL Fetch API Example</title>
</head>
<body>
<script>
const endpoint = 'https://geodb-cities-graphql.p.rapidapi.com/';
const query = `{
countries(namePrefix: "America") {
edges {
node {
name
capital
flagImageUri
currencyCodes
}
}
}
}`;
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-RapidAPI-Key': '<YOUR_RAPIDAPI_KEY>'
},
body: JSON.stringify({
query: query
})
};
fetch(endpoint, options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
</script>
</body>
</html>

Please make sure to replace <YOUR_RAPIDAPI_KEY> with your actual RapidAPI key.

This code will send a GraphQL query to the GeoDB Cities API endpoint to fetch information about all countries whose name starts with "America". The response from the server will be logged into the console. If there is an error, it will also be logged into the console.

Wrap up

In summary, calling GraphQL APIs using the Fetch API is a powerful way to retrieve data from web servers and integrate it into web applications. Using the Fetch API, we can easily request GraphQL APIs and handle the response data in our applications.