Using the Javascript Fetch API with GraphQL
📣 Sponsor
Over the past few years, GraphQL has become the preeminent way to make APIs. As such queries to GraphQL APIs are becoming more and more prevalent across the web, but how do you do a request to a GraphQL API?
In this article, we'll look at the easiest way to do this with vanilla Javascript - via the fetch API.
GraphQL Request
For this example, we'll be assuming a very simple POST
request for GraphQL, which uses one variable. Here is what I'm looking to request:
{
title(type: $type)
age
}
The variable I want to send is $type: 'post'
.
Fetch API
Now let's put this into the fetch API. I'll cover two types, the version with variables, and the one without.
GraphQL Fetch API with Variables
We must define the variable before our query here, so we have the line query ($type: String)
in our body as well. Apart from that we can send all the GraphQL data via the body of the request.
Variables are defined separately.
fetch('http://localhost:4000/api', {
method: 'POST',
body: JSON.stringify({
query: `query ($type: String) {
title(type: $type)
articleAge
}`,
variables: {
type: 'post'
}
}),
headers: {
'content-type': 'application/json'
}
}).then(async (data) => {
// Console log our return data
console.log(await data.json());
});
GraphQL Fetch API without Variables
Similar to before, but we can totally omit the references to variables, and simply send our request in brackets:
fetch('http://localhost:4000/api', {
method: 'POST',
body: JSON.stringify({
query: `{
title
articleAge
}`
}),
headers: {
'content-type': 'application/json'
}
}).then(async (data) => {
// Console log our return data
console.log(await data.json());
});