GraphQL Tutorial: Using Github GraphQL API with Node.js
As of API v4 Github is using GraphQL as a query language for their API. This gives the users more power and flexibility to ask exactly what they need from the API (it also gives you more public data compared to API v3, such as closed issues count).
While GraphQL comes with a lot of benefits it can be quite confusing to get going. This tutorial will help you get started with the Github GraphQL API.
Start by using a request helper library.
Because the Node.js standard HTTP library can be a bit verbose we'll use the node-fetch
module. It uses the same API as the fetch API that is used by modern browsers.
Install node-fetch
npm install node-fetch --save
Generating an access token
To authenticate the requests to the API, you need to generate a personal access token. Follow this guide on how to do it from the Github UI.
Once the token has been generated make sure to save it somewhere or keep the tab open because once you close the tab, you cannot see that token anymore.
Write your GraphQL query
We won't be focusing on learning GraphQL in this tutorial so we'll use this query to find the closed issues count from the isaacs/github
repository.
query {
repository(owner:"isaacs", name:"github") {
issues(states:CLOSED) {
totalCount
}
}
}
You can learn more about the Graph query language from here.
Putting it together
To query data from a REST API you would send a GET request to a specific URL that defines the resource of interest.
To query data from a GraphQL API you need to instead send a POST request to a fixed URL, which in our case is https://api.github.com/graphql
with a JSON body containing a query parameter.
const fetch = require('node-fetch');
const accessToken = 'your_access_token_from_github';
const query = `
query {
repository(owner:"isaacs", name:"github") {
issues(states:CLOSED) {
totalCount
}
}
}`;
fetch('https://api.github.com/graphql', {
method: 'POST',
body: JSON.stringify({query}),
headers: {
'Authorization': `Bearer ${accessToken}`,
},
}).then(res => res.text())
.then(body => console.log(body)) // {"data":{"repository":{"issues":{"totalCount":247}}}}
.catch(error => console.error(error));
Conclusion
While many GraphQL practices might seem counterintuitive to how you have been using APIs in the past, it's quite simple once you get used to it. Hopefully, this tutorial helped you make that very first request to a GraphQL API.