Created
September 7, 2017 21:07
-
-
Save singingwolfboy/69289b352738c6280b533e843ba3e332 to your computer and use it in GitHub Desktop.
Prints the labels from a GitHub repository, one per line.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you want to genericize the snippet, you could change line 28 to match GitHub's sample syntax for labels.
So: