The world around us is ruled by REST (Representational State Transfer) APIs. I want to dive into different examples to show how nice this technology is.
The Bash GitHub Example
Have you ever used REST in a bash script? Let’s use the GitHub REST API to find the latest commit hash of a certain repository:
repo="fmtlib/fmt"
last_commit_hash=$(curl -s "https://api.github.com/repos/$repo/commits" | jq -r '.[0].sha')b
echo "$last_commit_hash"
Have you ever wondered what repositories on GitHub have the most stars?
REPO_COUNT=10
GITHUB_API_URL="https://api.github.com/search/repositories?q=stars:>1&sort=stars&order=desc&per_page=$REPO_COUNT"
curl -s "$GITHUB_API_URL" | jq '.items[] | {name, html_url, stars: .stargazers_count, description}'
As a fan of the Bazel build system, I want to see only repositories that contain a MODULE.bazel file:
curl -s "https://api.github.com/search/code?q=filename:MODULE.bazel+in:path&sort=indexed&order=desc&per_page=10"
As a feedback from the above curl command, I get:
{
"message": "Requires authentication",
"errors": [
{
"message": "Must be authenticated to access the code search API",
"resource": "Search",
"field": "q",
"code": "invalid"
}
],
"documentation_url": "https://docs.github.com/rest/search/search#search-code"
}
A GitHub Personal Access Token needs to be set first — once you have this you can write:
REPO_COUNT=10
# Your GitHub Personal Access Token
GITHUB_TOKEN="<PASTE_YOUR_TOKEN_HERE>"
# GitHub API URL for searching repositories with MODULE.bazel sorted by stars
GITHUB_API_URL="https://api.github.com/search/code?q=filename:MODULE.bazel+in:path&sort=indexed&order=desc&per_page=$REPO_COUNT"
# Make a request to GitHub API using the token for authentication and parse the JSON response
curl -H "Authorization: token $GITHUB_TOKEN" -s "$GITHUB_API_URL" | jq '.items[] | {repository_name: .repository.full_name, file_url: .html_url, stars: .repository.stargazers_count, description: .repository.description}'
The results are not sorted by GitHub Stars, but you get the idea.