Making GraphQL queries with the Fetch API
Query a GraphQL API using JavaScript's Fetch API.
You can query a GraphQL API using JavaScript's built-in fetch API, without any libraries or dependencies.
What is the Fetch API?
The Fetch API provides an interface for fetching resources (including those across the network). Fetch provides a generic definition of Request and Response objects (and other things involved with network requests).
Fetch is a client-side API attached to the window and thus not available directly within Node.js. However you can use libraries like Node Fetch to bring the Fetch API into Node.js server-side code.
If you need to make a call to a API Connect for GraphQL as a Service API, it is highly recommended that you do so on the server-side or via a server-less function to protect your API key.
Querying a GraphQL API using Fetch
The fetch() method has only one mandatory argument, the path to the resource to
fetch. The following example shows how to call the public Rick and Morty API using
fetch():
fetch('https://rickandmortyapi.com/graphql')
This query returns a Promise that resolves to the Response for
that request. This happens as soon as the server responds with headers, even if the server response
is an HTTP error status.
Initoptions object-
You can optionally pass in an
initoptions object as the second argument (for example, to pass the HTTP request method and headers). - HTTP request methods
-
In most cases, GraphQL queries are performed as a
POSTrequest:fetch('https://rickandmortyapi.com/graphql', { method: 'POST', }) - Headers
-
HTTP headers let the client and the server pass additional information with an HTTP request or response. An HTTP header consists of its case-insensitive name followed by a colon (
:) and its value.For example, the type of the body of the request is indicated by the
Content-Typeheader. TheContent-Typefor GraphQL requests isapplication/json:fetch('https://rickandmortyapi.com/graphql', { method: 'POST', headers: { "Content-Type": "application/json" }, })Note: You can send API keys using theAuthorizationheader, but this is not recommended because your keys are then exposed to anyone who can view that header. - Body
-
The
Bodyof the Fetch API represents the body of the response/request. It enables you to declare its content type and how it should be handled.The example includes the
charactersquery in thebodyand stringifies it:fetch('https://rickandmortyapi.com/graphql', { method: 'POST', headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query: `{ characters { results { name } } }` }) })
Accessing the Query Results
Since a Fetch API call results in a JavaScript Promise, you must use then() or
await to handle the asynchronous results.
The following example shows the use of then():
fetch('https://rickandmortyapi.com/graphql', {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
query: `{
characters {
results {
name
}
}
}`
})
})
.then(res => res.json())
.then(res => console.log(res.data.characters.results))
You can achieve the same result using JavaScript's await to wait for the promise
to resolve:
async function getCharacters() {
let results = await fetch('https://rickandmortyapi.com/graphql', {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
query: `{
characters {
results {
name
}
}
}`
})
})
let characters = await results.json();
console.log(characters.data)
}
getCharacters()