Using Fetch to Make GraphQL Queries
Published in
Blog/en
on10/13/2023
.
You can query a GraphQL API using JavaScript's built-in fetch API in a simple way, without any libraries or dependencies.
Fetch API
You can query a GraphQL API using JavaScript's built-in fetch
API in a simple way, without any libraries or dependencies.`
First, we should put our GraphQL API URL in the fetch()
POST method.
For example, the GraphQL API URL for GitHub is https://api.github.com/graphql
, so we can get:
fetch("https://api.github.com/graphql", {
method: "POST",
})
Headers
Then, we should set our request headers. GraphQL requires the Content-Type
of the request should be application/json
.
Some API (like GitHub) also requires bringing a token to request.
fetch('https://github.com/graphql', {
method: 'POST',
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer <Token>",
},
})
Body
One of the things that is different from REST API is GraphQL can let developers decide what kind of data should respond.
The body should be in JSON format and a key named query
which has query params in it, we use JSON.stringify()
to convert object
to string
to make the request in fetch()
.
fetch('https://github.com/graphql', {
method: 'POST',
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer <Token>",
},
body: JSON.stringify({
// GraphQL, this query decides to get the first 6 discussions in the repo, responds with their title and URL.
query: `
query {
repository(owner: "ocoke", name: "Biscus") {
discussions(first: 6) {
nodes {
title
url
}
}
}
}`,
}),
}).then(res => res.json()).then(res => res.data)
Here we got the data from GraphQL API via fetch()
.