DEV Community

Peter Cooper
Peter Cooper

Posted on

How to Look at Your GitHub API Rate Limits

If you're using any GitHub client library worth its salt, it'll have a way to look at your current rate limits and expiry times. I have lots of tools using my GitHub account, however, and wanted an independent way to look at this data.

Luckily, if you have a Personal Access Token (PAT) it's easy to do so.

Place your personal access token in ~/.githubtoken (or any file of your choice) and then you can do this:

curl https://api.github.com/rate_limit -H "Authorization: token $(cat ~/.githubtoken)"
Enter fullscreen mode Exit fullscreen mode

However, I wanted to be able to use the information in a Ruby script and to show the number of seconds until a quota were to reset, so this Ruby code fits the bill:

require 'http'
require 'json'

TOKEN = File.read(ENV['HOME'] + "/.githubtoken").strip

res = HTTP["Authorization" => "token #{TOKEN}"].get("https://api.github.com/rate_limit")
rates = JSON.parse(res.to_s)

def convert_epoch_to_seconds_remaining(r)
  r["resets_in_seconds"] = (Time.at(r["reset"].to_i) - Time.now).ceil if r["reset"]
  r.values.each { |rr| convert_epoch_to_seconds_remaining(rr) if rr.is_a?(Hash) }
end

convert_epoch_to_seconds_remaining(rates)

puts rates.to_json
Enter fullscreen mode Exit fullscreen mode

The only dependency is the http gem, but you should have this anyway as it's fantastic. If you'd rather have no dependencies, you could use open-uri like so:

require 'json'
require 'open-uri'

TOKEN = File.read(ENV['HOME'] + "/.githubtoken").strip

res = open("https://api.github.com/rate_limit", "Authorization" => "token #{TOKEN}").read
rates = JSON.parse(res.to_s)

def convert_epoch_to_seconds_remaining(r)
  r["resets_in_seconds"] = (Time.at(r["reset"].to_i) - Time.now).ceil if r["reset"]
  r.values.each { |rr| convert_epoch_to_seconds_remaining(rr) if rr.is_a?(Hash) }
end

convert_epoch_to_seconds_remaining(rates)

puts rates.to_json
Enter fullscreen mode Exit fullscreen mode

Top comments (0)