DEV Community

Francesco Menghi
Francesco Menghi

Posted on

Fetching the Github API

This week my latest PR for telescope was merged. It all started with an issue to add Github stats to the new Telescope dashboard.

The dashboard is currently showing the material-dashboard template and we are going to add relevant information to it one PR at the time.

Material Dashboard

To add relevant stats I had to go through the Github API to see what data I could get from it.

Commit count

I first found a way to get the weekly and yearly commit count. This request returns and array of the number of commits per week over the last year.

Here is the request using curl:

curl \
  -H "Accept: application/vnd.github.v3+json" \
  https://api.github.com/repos/Seneca-CDOT/telescope/stats/participation
Enter fullscreen mode Exit fullscreen mode

And here is with fetch in Javascript:

fetch(`https://api.github.com/repos/Seneca-CDOT/telescope/stats/participation`, {
    headers: { Accept: 'application/vnd.github.v3+json' },
  });
  .then((res) => res.json())
  .then((data) => {
    // use received data
  })
Enter fullscreen mode Exit fullscreen mode

Weekly commits activity

The second data I wanted was the total lines added and lines removed for the week. I found this by fetching the weekly commit activity:

Taking the last element of the array gives us the UNIX timestamp, the lines added and the lines removed:

[
  1636848000,
  876,
  -349
]
Enter fullscreen mode Exit fullscreen mode

Latest author

To get the author of the latest commit, I had to fetch the list of commits:

The response includes a lot of information about each commit, so I only focused on the information I needed:

  • name
  • username
  • profile picture
{
  "commit": {
    "author": {
      "name": "Francesco Menghi",
    },
  },
  "author": {
    "login": "menghif",
    "avatar_url": "https://avatars.githubusercontent.com/u/53121061?v=4",
  },
}
Enter fullscreen mode Exit fullscreen mode

Total Contributors

Finally I wanted a way to get the total number of contributors of the repo. I fetched the repository contributors with 1 result per page and then retrieved the number of pages returned in the response header. Thanks David!

fetch(`https://api.github.com/repos/Seneca-CDOT/telescope/contributors?per_page=1`, {
  headers: { Accept: 'application/vnd.github.v3+json' },
});
.then((res) => res.headers.get('link'))
.then((data) => {
  const contributors = data.match(/.*"next".*&page=([0-9]*).*"last".*/)[1];
})
Enter fullscreen mode Exit fullscreen mode

Putting it all together

This is the end result:

Telescope Dashboard

The Javascript code with all the fetch requests is available here.

I am pleased with the result, but it is only the first step. I am sure that other students will find bugs to fix and will have more to contribute to it. I'm looking forward to how the dashboard will look once "finished".

Top comments (0)