Last active
March 29, 2024 06:08
-
-
Save ranabhat/61100bb325ba79078a049e50c96da6c4 to your computer and use it in GitHub Desktop.
Simple example on how to use web APIs in Python3.
This file contains 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
import requests # importing libraries for working with HTTP requests | |
import json | |
api_url_base = 'https://api.github.com/' # string that starts off every URL in the GitHub API | |
#response = requests.get(api_url_base) | |
#print(response.headers) | |
headers = {'Content-Type': 'application/json', | |
'Accept': 'application/vnd.github.v3+json' | |
} | |
def get_repos(username): | |
''' | |
This function accepts a username as its argument | |
This function will get the list of github repos | |
''' | |
api_url = '{}users/{}/repos'.format(api_url_base, username) | |
print(api_url) | |
response = requests.get(api_url, headers=headers) | |
#data = response.json() | |
#print(data.name) | |
# code should always check the HTTP status code for any response before trying to do anything with it. | |
# notherwise we find ourself wasting time troubleshooting with incomplete information. | |
if response.status_code == 200: | |
# Getting JSON from an API request | |
# Get the response data as a object. | |
data = response.json() | |
#return (response.content) # in bytes format | |
print(len(data)) # find number of repos | |
return ([data[x]['name'] for x in range(len(data))]) # return the list of the name of the repositories of the relevant user | |
#return ([(data[x]['name'],data[x]['description']) for x in range(len(data))]) # return the list of the tuple including name and description of the repositories of the relevant user | |
else: | |
print('[!] HTTP {0} calling [{1}]'.format(response.status_code, api_url)) | |
return None | |
#Testing | |
repo_list = get_repos('jwasham') | |
if repo_list is not None: | |
print(repo_list) | |
else: | |
print('No Repo List Found') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment