Skip to content

Commit 6f913ff

Browse files
Create Assignment13.3.py
1 parent 45c5c83 commit 6f913ff

1 file changed

Lines changed: 56 additions & 0 deletions

File tree

PFE/PDS/Assignment13.3.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
'''
2+
Calling a JSON API
3+
4+
In this assignment you will write a Python program that will prompt for a location, contact a web service and retrieve JSON for the
5+
web service and parse that data, and retrieve the first place_id from the JSON. A place ID is a textual identifier that uniquely identifies
6+
a place as within Google Maps.
7+
8+
http://py4e-data.dr-chuck.net/json?
9+
10+
To call the API, you need to include a key= parameter and provide the address that you are requesting as the address= parameter that is
11+
properly URL encoded using the urllib.parse.urlencode() function
12+
'''
13+
14+
15+
import urllib.request, urllib.parse, urllib.error
16+
import json
17+
api_key = False
18+
if api_key is False:
19+
api_key = 42
20+
serviceurl = 'http://py4e-data.dr-chuck.net/json?'
21+
address = input('Enter location: ')
22+
if len(address) < 1:
23+
print("Try again with passing correct URL")
24+
exit()
25+
#to encode address adding it to dictionary and preparing entire url
26+
parms = dict()
27+
parms['address'] = address
28+
if api_key is not False: parms['key'] = api_key
29+
url = serviceurl + urllib.parse.urlencode(parms)
30+
#printing the prepared url
31+
print('Retrieving ',url)
32+
#read the given url and count and print total number of characters
33+
urlData = urllib.request.urlopen(url).read().decode('utf-8')
34+
print('Retrieved', len(urlData), 'characters')
35+
36+
#parsing the data
37+
try:
38+
info = json.loads(urlData)
39+
except:
40+
info = None
41+
if not info or 'status' not in info or info['status'] != 'OK':
42+
print('==== Failure To Retrieve ====')
43+
print(urlData)
44+
exit()
45+
46+
place_id=info["results"][0]["place_id"]
47+
print('Place id ',place_id)
48+
49+
50+
'''
51+
Desired Output:
52+
Enter location: South Federal University
53+
Retrieving http://py4e-data.dr-chuck.net/json?address=South+Federal+University&key=42
54+
Retrieved 2505 characters
55+
Place id ChIJ0V94rPl_bIcRqLdrlbjFMDk
56+
'''

0 commit comments

Comments
 (0)