Alert This post is over a year old, some of this information may be out of date.

#DevHack: Fetching sponsors via the GitHub GraphQL API

post

To automate the roll-up of sponsors for Front Matter on the website. I started to look through the GitHub Rest API documentation to check it could receive this kind of information. Unfortunately, the Rest API does not provide you with this information, so I went to where the cool kids go these days, GraphQL. The GitHub GraphQL API delivers you more precise and flexible queries and is your go-to place these days.

Info

The best part of the GitHub GraphQL is a GraphQL Explorer available, allowing you to try out your queries.

GraphQL Explorer is excellent when you have never worked with the API. Via the explorer, I found the correct query to use.

Authentication

To retrieve your sponsors, you first need to have an OAuth Token. For this, you can create a personal access token. You can follow the steps in “Creating a personal access token” documentation.

Important

Make sure you select read:user and read:email to retrieve the sponsor information.

Fetching the GraphQL data

The GraphQL query for retrieving your sponsors looks as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
query SponsorQuery {
  viewer {
    sponsors(first: 100) {
      edges {
        node {
          ... on User {
            id
            name
            url
            avatarUrl
          }
        }
      }
    }
  }
}

On the Front Matter website, I retrieve this information via my custom API, which performs a POST request to the https://api.github.com/graphql API.

The code looks as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const response = await fetch(`https://api.github.com/graphql`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': `token ${process.env.GITHUB_AUTH}`
  },
  body: JSON.stringify({
    query: `query SponsorQuery {
      viewer {
        sponsors(first: 100) {
          edges {
            node {
              ... on User {
                id
                name
                url
                avatarUrl
              }
            }
          }
        }
      }
    }`
  })
});

if (response && response.ok) {
  const data = await response.json();
  // Start working with the data
}
Info

If you want, you can check out the API code for the website. You can see the sponsor API file.

Comments

Back to top