python get github file content

Solutions on MaxInterview for python get github file content by the best coders in the world

showing results for - "python get github file content"
Emelie
12 May 2016
1import requests
2import base64
3import json
4
5
6def constructURL(user = "404",repo_name= "404",path_to_file= "404",url= "404"):
7  url = url.replace("{user}",user)
8  url = url.replace("{repo_name}",repo_name)
9  url = url.replace("{path_to_file}",path_to_file)
10  return url
11
12user = '<provide value>'
13repo_name = '<provide value>'
14path_to_file = '<provide value>'
15json_url ='https://api.github.com/repos/{user}/{repo_name}/contents/{path_to_file}'
16
17json_url = constructURL(user,repo_name,path_to_file,json_url) #forms the correct URL
18response = requests.get(json_url) #get data from json file located at specified URL 
19
20if response.status_code == requests.codes.ok:
21    jsonResponse = response.json()  # the response is a JSON
22    #the JSON is encoded in base 64, hence decode it
23    content = base64.b64decode(jsonResponse['content'])
24    #convert the byte stream to string
25    jsonString = content.decode('utf-8')
26    finalJson = json.loads(jsonString)
27else:
28    print('Content was not found.')
29
30for key, value in finalJson.items():
31    print("The key and value are ({}) = ({})".format(key, value))
32
similar questions
queries leading to this page
python get github file content