How to show download statistics of GitHub releases with JS
GitHub is a leading platform for software collaboration, and offers a lot of features for this end. Beyond its core functionalities, GitHub also offers a rich REST API that provides public access to a wealth of information about its content. Leveraging this API allows seamless integration if repository information to project websites.
In this example, we use the releases api endpoint to count the number of downloads across different releases, and show the number of downloads a the website.
The Code
let repoName = "kyberturvakirja/kyberturvakirja"; // Repository name
let url = `https://api.github.com/repos/${repoName}/releases?per_page=100`;
let request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function () {
let releases = JSON.parse(this.response);
let sum = 0;
// Count downloads for each asset of every release
if (Array.isArray(releases)) {
for (const release of releases) {
for(const asset of release['assets']) {
sum += asset['download_count'];
}
}
} else if (releases['assets'] !== undefined) {
for(const asset of releases['assets']) {
sum += asset['download_count'];
}
}
let output = "Downloaded " + sum + " times"
document.getElementById('downloads').innerHTML = output;
};
request.send();
What does it do?
The API endpoint for release information is /repos/{owner}/{repo}/releases on api.github.com and a simple GET request without authentication suffices. We can add a large per_page parameter for good measure, to count more than 30 releases into the past.
The query returns a large JSON with a bunch of data. This JSON can be parsed to extract various details such as release dates, names, and download links, for instance.
The example code above runs through the different releases and counts the downloads of each asset in each release. The total number is written to the HTML element with the ID ‘downloads’, which can be styled elsewhere.
Uses of JavaScript-based API access
JavaScript’s client-side nature makes it a good choice for incorporating live information into any website, including static sites. This approach allows real-time data retrieval and presentation directly within users’ browsers.
By integrating JavaScript code into the webpage’s HTML, even static sites can become interactive, showcasing dynamic project information without requiring intricate server-side configurations.
For large websites, or information that repeats on multiple pages, a caching system would be useful.