/
NPRApi.py
executable file
·37 lines (28 loc) · 988 Bytes
/
NPRApi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from urllib.request import urlopen
import json
#1007 Science topics
#1019 Technology topics
def main():
url = 'http://api.npr.org/query?apiKey='
urlKey = 'myKey'
urlNumberResults = '&numResults=5'
urlFormat = '&format=json'
urlId = '&id=1019'
urlRequireAssets = '&requireAssets=images,audio,text'
url += urlKey + urlNumberResults + urlFormat + urlId + urlRequireAssets
response = getResponse(url)
json_obj = parseToJson(response)
print(json_obj['list']['title']['$text'] + "\n")
for story in json_obj['list']['story']:
print(story['title']['$text'] + "\n")
print(story['teaser']['$text'])
print(story['storyDate']['$text'] + "\n")
for paragraph in story['text']['paragraph']:
print(paragraph['$text'] + "\n")
print("-------------------------------" + "\n")
def getResponse(url):
return str(urlopen(url).read().decode('utf-8'))
def parseToJson(response):
return json.loads(response)
if __name__ == "__main__":
main()