ScottSpence.com

Scott's Thoughts Pamphlet!

Get GraphQL Data Using Axios

Ok this is a little snippet I’ve got set up to query data from the GitHub GraphQL API.

I use this for getting data to work with in data visualisation tools, I’ve done it a couple of times noe with my Gatsby site but now I’m attempting to do it in a serverless function.

Here’s the snippet I’m using from SO:

1import axios from 'axios'
2import query from './query'
3
4export async function getGitHubData() {
5 const gitHubCall = await axios.post(
6 `https://api.github.com/graphql`,
7 {
8 query,
9 },
10 {
11 headers: {
12 'Content-Type': 'application/json',
13 Authorization: 'token ' + process.env.GITHUB_TOKEN,
14 },
15 }
16 )
17 return gitHubCall.data.data
18}

The GITHUB_TOKEN is needed for access to the GitHub GraphQL endpoint.

For the GITHUB_TOKEN you can create that from your GitHub account, the steps are, from your github profile page:

1# Settings >
2# Developer Settings>
3# Personal access tokens>
4# Generate new token>
5# select repo access

Or use the link here: https://github.com/settings/tokens/new

The query can be something really simple to begin with to validate it’s working:

1export default `
2{
3 viewer {
4 id
5 bio
6 }
7}
8`

To consume the data somewhere else in your codebase:

1import { getGitHubData } from './github-query'
2
3async function dataGet() {
4 const data = await getGitHubData()
5 console.log('=====================')
6 console.log(data)
7 console.log('=====================')
8}

If the query you’re using takes variables then add that to the variables object in the Axios request, in this example I’ve hardcoded in my GitHub username:

1import axios from 'axios'
2import query from './query'
3
4export async function getGitHubData() {
5 const gitHubCall = await axios.post(
6 `https://api.github.com/graphql`,
7 {
8 // query using ES6+ shorthand
9 // query can be like query: query,
10 query,
11 variables: {
12 username: 'spences10',
13 },
14 },
15
16 {
17 headers: {
18 'Content-Type': 'application/json',
19 Authorization: 'token ' + process.env.GITHUB_TOKEN,
20 },
21 }
22 )
23 return gitHubCall.data.data
24}

The GraphQL query will look something like this:

1export default `
2query BIO_QUERY($username: String!) {
3 user(login: $username) {
4 id
5 bio
6 }
7}
8`

Back to Top


Scott Spence

Built with Gatsby · Hosted on Vercel · 2021