Published on January 27, 2023 •
Updated on June 13, 2024
While browsing the Ant Design documentation, I noticed that they show the GitHub contributors of a file at the bottom of the page. I thought it was a nice feature and wanted to blog about it.
The GitHub API is a great resource to get information about a repository. It is very well-documented and has a lot of endpoints. The endpoint we are interested in is the commits endpoint. It returns a list of commits for a repository. We can use the path parameter to filter the commits by a file path and filter the commits by a specific author with the author parameter. For example, the following request returns the commits for the README.md file in the gatsby repository:
We will create a mini frontend to show getting the commits for a file and showing the contributors. We will use Alpine.js and PicoCSS to create the frontend because they are small and easy to use. First, create an index.html file with the following content:
Here we have a simple HTML page that looks like this:
Now I will save a sample response as test.json because I can’t send a request every time I refresh the page. That will be a bad thing to do and we can get a rate limited.
Getting the commits
In the scripting part, we will first define a constant to the API URL we want.
We then initialize the store with the Alpine.store() function.
After that, we will fetch the commits and parse them to JSON.
We will create a function to format the commits to the format we want. We will use the reduce() function to get the unique contributors and the map() function to get the commits for each contributor.
Finally, we will call the format() function with the commitsData and set the contribs store to the result.
Our final script will look like this:
Now we will create a component to show the contributors. We will use the x-for directive to loop through the contributors and show them.
And save the file. Now when we refresh the page,
and Voila! We have our contributors.
Conclusion
In this tutorial, we learned how to get the contributors of a file in a GitHub repository using the GitHub API. We also learned how to use Alpine.js to show the contributors on a simple HTML page. I hope this tutorial was helpful to you and get a taste of Alpine.js’ simplicity and power.