Skip to content

Instantly share code, notes, and snippets.

@singingwolfboy
Created September 7, 2017 21:07
Show Gist options
  • Save singingwolfboy/69289b352738c6280b533e843ba3e332 to your computer and use it in GitHub Desktop.
Save singingwolfboy/69289b352738c6280b533e843ba3e332 to your computer and use it in GitHub Desktop.
Prints the labels from a GitHub repository, one per line.
# This requires the Requests module, which is a 3rd-party module: python-requests.org
# Install with: `pip install requests`
import requests
def paginated_get(url):
"""
Create a generator of objects from the GitHub API,
while traversing Link headers for pagination.
"""
response = requests.get(url)
response.raise_for_status() # raise an exception if we don't get 200 OK
while response:
results = response.json()
for result in results: # loop over list of labels in the reponse,
yield result # and yield them one at a time
# Is this content paginated? If so, get the next page and keep yielding.
next_url = response.links.get('next', {}).get('url', None)
if next_url:
response = requests.get(next_url)
# Now we have a new `response` variable, so the `while response`
# loop will continue looping with it.
else:
response = None
# Now the `response` variable is None, so the `while response`
# loop will end.
url = "https://api.github.com/repos/kubernetes/kubernetes.github.io/labels"
for label in paginated_get(url):
print(label.get('name'))
@zacharysarah
Copy link

If you want to genericize the snippet, you could change line 28 to match GitHub's sample syntax for labels.

So:

# Replace the values of :owner and :repo as needed
url = "https://api.github.com/repos/:owner/:repo/labels"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment